簡體   English   中英

創建字典,其中鍵來自列表,值是另一個列表中相應元素的總和

[英]Create dictionary where keys are from a list and values are the sum of corresponding elements in another list

我有兩個列表L1和L2。 L1中的每個唯一元素是在第二列表L2中具有值的鍵。 我想創建一個字典,其中值是L2中與L1中相同鍵相關聯的元素的總和。

我做了以下但我對這段代碼並不感到自豪。 有沒有更簡單的pythonic方法呢?

L = [2, 3, 7, 3, 4, 5, 2, 7, 7, 8, 9, 4] # as L1
W = range(len(L)) # as L2

d = { l:[] for l in L }
for l,w in zip(L,W): d[l].append(w)
d = {l:sum(v) for l,v in d.items()}

編輯:

問:我如何知道L2的哪個元素與L1的給定關鍵元素相關聯?

答:如果他們有相同的索引。 例如,如果元素7在L1中重復3次(例如L1 [2] == L1 [7] == L1 [8] = 7),那么我希望鍵7的值為L2 [2] + L2 [7] + L2 [8]

你循環遍歷列表時可以使用enumerate()來訪問項目的索引,並使用collections.defaultdict() (通過傳遞int作為缺少的函數,它將在第一次被評估為0)以保留項目和遇到重復鍵時添加值:

>>> from collections import defaultdict

>>> d = defaultdict(int)
>>> for i,j in enumerate(L):
...     d[j]+=i
... 
>>> d
defaultdict(<type 'int'>, {2: 6, 3: 4, 4: 15, 5: 5, 7: 17, 8: 9, 9: 10})

如果您不需要list s的中間dict ,則可以使用collections.Counter

import collections
L = [2, 3, 7, 3, 4, 5, 2, 7, 7, 8, 9, 4] # as L1
W = range(len(L)) # as L2

d2 = collections.Counter()
for i, value in enumerate(L):
    d2[value] += i

其行為類似於普通字典:

Counter({2: 6, 3: 4, 4: 15, 5: 5, 7: 17, 8: 9, 9: 10})

希望這可以幫到你。

L = [2, 3, 7, 3, 4, 5, 2, 7, 7, 8, 9, 4] # as L1
dict_a = dict.fromkeys(set(L),0)
for l,w in enumerate(L):    
    dict_a[w] = int(dict_a[w]) + l

暫無
暫無

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

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