list1을 list2로 변환하는 방법?
list1 =[[1, 11], [2, 22], [3, 33], [4, 44]]
list2 = [[{1:2},{11:22}],[{3:4},{33:44}]]
리스트 2의 키는리스트 1의 홀수 요소이고리스트 2의 값은리스트 1의 짝수입니다.
나는 아래와 같이 시도했지만 다른 목록을 얻습니다 .3.
def f(list1):
newlist=[]
for i in range(0, len(list1), 2):
dict1={}
for j,key in enumerate (list1[i]):
dict1[key]=list1[i+1][j]
newlist.append(dict1)
print newlist
f(list1)
[{1: 2, 11: 22}, {1: 2, 11: 22}, {33: 44, 3: 4}, {33: 44, 3: 4}]
목록 이해력으로 :
list1 = [[1, 11], [2, 22], [3, 33], [4, 44]]
list2 = [[{tup[0]: tup[1]} for tup in zip(*list1[i:i+2])] for i in range(0, len(list1), 2)]
# Prints as [[{1: 2}, {11: 22}], [{3: 4}, {33: 44}]]
편집 : 이것은 조금 더 깨끗합니다 (아마도 비단뱀 적).
list2 = [[dict([tup]) for tup in zip(*sublist)] for sublist in zip(list1[0::2], list1[1::2])]
Edit2 : 목록 이해력은이 중첩 된 for 루프와 동일합니다.
list1 =[[1, 11], [2, 22], [3, 33], [4, 44]]
list2 = list()
# Iterate over list1 two by two, first round: sublist = ([1,11], [2,22])
for sublist in zip(list1[0::2], list1[1::2]):
inner_result = list()
# Second loop equivalent to for tup in zip(sublist[0], sublist[1])
for tup in zip(*sublist): # First round, tup will be (1,2) then (11, 22)
# Make dictionary from tuple, for first tuple this is
# equivalent to: dict([(1,2)]) == {1: 2}
new_dict = dict([tup])
inner_result.append(new_dict)
list2.append(inner_result)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다