簡體   English   中英

從列表列表中的Dict理解python

[英]Dict Comprehension python from list of lists

我有一個列表列表,我正在嘗試從列表中創建一個字典。 我知道如何使用這種方法。 使用Python創建包含列表列表的字典

我要做的是使用第一個列表中的元素作為鍵來構建列表,具有相同索引的其余項目將是值列表。 但我無法弄清楚從哪里開始。 每個列表的長度相同,但列表的長度各不相同

exampleList = [['first','second','third'],['A','B','C'], ['1','2','3']]

resultDict = {'first':['A','1'],'second':['B','2'],'third':['C','3']}

解壓縮和使用zip后跟dict理解以獲得第一個元素的映射似乎是可讀的。

result_dict = {first: rest for first, *rest in zip(*exampleList)}

使用zip(*exampleList)解壓縮值並使用鍵值對創建字典。

dicta = {k:[a, b] for k, a, b in zip(*exampleList)}
print(dicta)
# {'first': ['A', '1'], 'second': ['B', '2'], 'third': ['C', '3']}

如果有更多名單:

dicta = {k:[*a] for k, *a in zip(*exampleList)}
# {'first': ['A', '1', 4], 'second': ['B', '2', 5], 'third': ['C', '3', 6]}

如果你不關心列表與元組,那就像使用zip兩次一樣簡單:

result_dict = dict(zip(example_list[0], zip(*example_list[1:])))

否則,您需要通過調用map

result_dict = dict(zip(example_list[0], map(list, zip(*example_list[1:]))))

exampleList可以是任何長度時,請注意這種情況。

exampleList = [['first','second','third'],['A','B','C'], ['1','2','3'],[4,5,6]]

z=list(zip(*exampleList[1:]))
d={k:list(z[i])  for i,k in enumerate(exampleList[0])}
print(d)

產量

{'first': ['A', '1', 4], 'second': ['B', '2', 5], 'third': ['C', '3', 6]}

zip功能可能正是您所需要的。

exampleList = [['first','second','third'],['A','B','C'], ['1','2','3']]
d = {x: [y, z] for x, y, z in zip(*exampleList)}
print(d)
#{'first': ['A', '1'], 'second': ['B', '2'], 'third': ['C', '3']}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM