![](/img/trans.png)
[英]How can I convert a dictionary that has frozensets as keys and integers as values into a list of dictionaries?
[英]How can I convert a list of lists to a dictionary whose keys are integers and values are the index of the sublist to which the integer belongs?
我有一個列表列表,其中每個 integer 0..N 恰好屬於外部列表中的一個列表。 例如,如果 N=6,我有類似的東西
L=[[0,4,5],[2,3],[1,6]]
我希望字典如下所示:
{0:0, 1:2, 2:1, 3:1, 4:0, 5:0}
例如,key:value 對 2:1 表示 2 屬於 L[1]。
有沒有一種簡單的方法可以做到這一點?
L = [[0, 4, 5], [2, 3], [1, 6]]
result = {value: i for i, values in enumerate(L) for value in values}
print(result)
Output
{0: 0, 4: 0, 5: 0, 2: 1, 3: 1, 1: 2, 6: 2}
這相當於:
result = {}
for i, values in enumerate(L):
for value in values:
result[value] = i
在我看來,這里的關鍵是使用 enumerate 來訪問L
的索引和元素。
L=[[0,4,5],[2,3],[1,6]]
result = dict()
for i,l in enumerate(L):
for item in l:
result[item]=i
print(result)
這將產生 output ,如:
{0: 0, 1: 2, 2: 1, 3: 1, 4: 0, 5: 0, 6: 2}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.