繁体   English   中英

压缩类似键以构建字典时如何对值求和

[英]How to sum values when zipping similar key to build a dict

我有A = [a, b, c, d, a, d, c]B=[1, 2, 3, 4, 5, 6, 7]

为什么dict(zip(A,B))不返回{'a': 6, 'b': 2, 'c': 10, 'd': 10}

如何使它起作用?

使用简单的迭代

前任:

A = ["a", "b", "c", "d", "a", "d", "c"] 
B= [1, 2, 3, 4, 5, 6, 7]

result = {}
for a, b in zip(A, B):
    if a not in result:
        result[a] = 0
    result[a] += b
print(result)

或者使用collections.defaultdict

前任:

from collections import defaultdict
result = defaultdict(int)
for a, b in zip(A, B):
    result[a] += b
pprint(result)

输出:

{'a': 6, 'b': 2, 'c': 10, 'd': 10}

dict只会覆盖值.. 你想要的不会那么容易。 你需要这样的东西:

#!/usr/bin/env python3
from collections import defaultdict

A = ["a", "b", "c", "d", "a", "d", "c"]
B = [1, 2, 3, 4, 5, 6, 7]

output = defaultdict(int)

for a,b in zip(A,B):
        output[a] += b

print(output)

结果:

defaultdict(<class 'int'>, {'a': 6, 'b': 2, 'c': 10, 'd': 10})

默认情况下, defaultdict会将每个新键的值设置为0 .. 允许我们在每个键上调用+=没有错误.. 给我们我们需要的总和。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM