我想使用串列理解從兩個嵌套串列中創建一個字典串列。我嘗試了不同的技術,但它不起作用。
a = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'] ]
b = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
期望的結果是
c = [ {'a':1, 'b':2, 'c':3}, {'d':4, 'e':5, 'f':6}, {'g':7, 'h':8, 'i':9} ]
我最后嘗試的是
c = [dict(zip(a,b)) for list1, list2 in zip(a,b) for letter, number in zip(list1,list2)]
uj5u.com熱心網友回復:
當你zip a和b時,它會創建一個可迭代的元組:
out = list(zip(a, b))
[(['a', 'b', 'c'], [1, 2, 3]),
(['d', 'e', 'f'], [4, 5, 6]),
(['g', 'h', 'i'], [7, 8, 9])]
現在,如果您查看上面的串列,應該清楚每對串列都是您想要的結果中字典的鍵和值。所以很自然,我們應該zip每一對:
for sublist1, sublist2 in zip(a,b):
print(list(zip(sublist1, sublist2)))
[('a', 1), ('b', 2), ('c', 3)]
[('d', 4), ('e', 5), ('f', 6)]
[('g', 7), ('h', 8), ('i', 9)]
上述結果表明每個元組都是所需字典中的鍵值對。
所以我們可以使用 dict 建構式而不是列印它們:
out = [dict(zip(sublist1, sublist2)) for sublist1, sublist2 in zip(a, b)]
輸出:
[{'a': 1, 'b': 2, 'c': 3}, {'d': 4, 'e': 5, 'f': 6}, {'g': 7, 'h': 8, 'i': 9}]
uj5u.com熱心網友回復:
您需要同時遍歷兩個串列,您可以通過zip將它們 ping 在一起然后zipping 每個串列并將其傳輸到dict.
你可以通過使用這個 oneliner 來實作
a = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'] ]
b = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
c = [dict(zip(l1, l2)) for l1, l2 in zip(a, b)]
# [{'a': 1, 'b': 2, 'c': 3}, {'d': 4, 'e': 5, 'f': 6}, {'g': 7, 'h': 8, 'i': 9}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/435221.html
標籤:Python python-3.x 列表 字典 列表理解
