[英]How to sum values when zipping similar key to build a dict
I have A = [a, b, c, d, a, d, c]
and B=[1, 2, 3, 4, 5, 6, 7]
我有
A = [a, b, c, d, a, d, c]
和B=[1, 2, 3, 4, 5, 6, 7]
Why dict(zip(A,B))
doesn't return {'a': 6, 'b': 2, 'c': 10, 'd': 10}
?为什么
dict(zip(A,B))
不返回{'a': 6, 'b': 2, 'c': 10, 'd': 10}
?
How to make it works?如何使它起作用?
Using a simple iteration使用简单的迭代
Ex:前任:
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)
Or using collections.defaultdict
或者使用
collections.defaultdict
Ex:前任:
from collections import defaultdict
result = defaultdict(int)
for a, b in zip(A, B):
result[a] += b
pprint(result)
Output:输出:
{'a': 6, 'b': 2, 'c': 10, 'd': 10}
dict
will just over-write the values.. what you want won't come so easily. dict
只会覆盖值.. 你想要的不会那么容易。 You'd need something like this:你需要这样的东西:
#!/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)
The result:结果:
defaultdict(<class 'int'>, {'a': 6, 'b': 2, 'c': 10, 'd': 10})
defaultdict
will set each new keys value to 0
by default.. allowing us to call +=
on each key without error.. giving us the sum we need.默认情况下,
defaultdict
会将每个新键的值设置为0
.. 允许我们在每个键上调用+=
没有错误.. 给我们我们需要的总和。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.