사전 목록으로 변환해야하는 다음 문자열이 있습니다.
'"Date","Volume/Length","Length/Width","Weight gm":"08-Dec-2018"," 23.19"," 2.13"," 1.32":"08-Jan-2019"," 22.70"," 5.22"," 1.02":'
이것을 수행하는 비단뱀적인 방법은 무엇입니까? 열쇠는"Date","Volume/Length","Length/Width","Weight gm"
먼저 문자열을 중첩 된으로 변환합니다 list
. 여기서 각 내부 list
는 행을 나타냅니다.
import re
string = '"Date","Volume/Length","Length/Width","Weight gm":"08-Dec-2018"," 23.19"," 2.13"," 1.32":"08-Jan-2019"," 22.70"," 5.22"," 1.02":'
nested_list = [[value.strip() for value in row.replace('"', '').split(',')] for row in string.strip(':').split(':')]
# Colons divide rows, so there shouldn't be any at the ends
그런 다음 list
각 내부가 list
이제 열을 나타내 도록 중첩을 전치합니다 . 각 열에서 첫 번째 요소는 열 이름이고 나머지는 해당 열의 값입니다. 이 스키마에 따라 슬라이싱을 수행하여 최종 키-값 쌍을 가져올 수 있습니다 dict
.
transposed_list = list(zip(*nested_list))
result = {column[0]: column[1:] for column in transposed_list}
# This part can be changed to list(column[1:]) if you want the inner elements to be lists
print(result)
산출:
{'Date': ('08-Dec-2018', '08-Jan-2019'),
'Volume/Length': ('23.19', '22.70'),
'Length/Width': ('2.13', '5.22'),
'Weight gm': ('1.32', '1.02')}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다