我在这里看到两个列表。
a = ['a','b','a']
b = [200,300,300]
当我这样打印时:
print dict(zip(a,b))
我明白了:
{'A': 300, 'B': 300}
如何根据键聚合值,以便我得到
{'A': 500, 'B': 300}
?
答案 0 :(得分:3)
result = {}
for k,v in zip (['a','b','a'], [200,300,300]):
result[k] = result.get(k,0) + v
print result
答案 1 :(得分:1)
from collections import Counter
a = ['a','b','a']
b = [200,300,300]
c = Counter()
for i, j in zip(a, b):
c[i] += j
print(c)
答案 2 :(得分:0)
我想一个明确的方法(每Python's Zen)来实现你的目标是:
from __future__ import print_function
a = ['a','b','a']
b = [200,300,300]
d = dict()
for place, key in enumerate(a):
try:
d[key] += b[place]
except KeyError:
d[key] = b[place]
print(d)
这给出了您的预期输出:
{'a':500,'b':300}
答案 3 :(得分:0)
您只需要为密钥和值迭代zip并将它们放入字典中。
a = ['a','b','a']
b = [200,300,300]
for key, val in zip(a,b):
if key in combined_dict:
combined_dict[key] += val
else:
combined_dict[key] = val
print(combined_dict)
=> {'a': 500, 'b': 300}
答案 4 :(得分:-1)
一种方法如下,避免使用zip功能,
aggregateDict = {}
a= ['a', 'b', 'a']
b=[200, 300, 200]
for i in range(len(a)):
aggregateDict[a[i]] = aggregateDict.get(a[i], 0) + b[i]
输出
{'a': 400, 'b': 300}