![](/img/trans.png)
[英]Pythonic way to create a dictionary from a list where the keys are the elements that are found in another list and values are elements between keys
[英]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.