Python 如何在压缩相似键以构建dict时求和值
我有Python 如何在压缩相似键以构建dict时求和值,python,python-3.x,Python,Python 3.x,我有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} 如何使其工作?使用简单的迭代 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] =
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}
如何使其工作?使用简单的迭代 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)
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}
或者使用
collections.defaultdict
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)
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}
输出:
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)
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(,{'a':6,'b':2,'c':10,'d':10})
默认情况下,
defaultdict
会将每个新键的值设置为0
。。允许我们在每个键上调用+=
,不会出错。。给我们所需的金额。…python无法读懂你的心思;它怎么知道你想把这些值相加,而不是,我不知道,把它们相乘?怎么知道'a':6
?@DirtyBit当一个键出现多次时,我想把每个值相加。非常感谢@Rakesh