我试图在两个dicts中计算列表元素值。当两个Dicts中存在密钥时,它会起作用,如果我删除一个密钥,它将抛出一个错误。是否有另一种方便的方法来组合dicts?
这有效:
from collections import Counter
B = Counter({'a':[3], 'b':[4], 'c':[5]})
C = Counter({'a':[19], 'b':[4], 'c':[5] })
print B+C
>>> Counter({'c': [5, 5], 'b': [4, 4], 'a': [3, 19]})
这不是:
from collections import Counter
B = Counter({'a':[3], 'b':[4], 'c':[5]})
C = Counter({'a':[19], 'b':[4] }) #<--- c removed
print B+C
>>> TypeError: can only concatenate list (not "int") to list
答案 0 :(得分:2)
字典更新方法怎么样?
>>> from collections import Counter
>>> A = Counter({})
>>> B = Counter({'a':[3], 'b':[4], 'c':[5]})
>>> C = Counter({'a':[19], 'b':[4] })
>>> A.update(B)
>>> A
Counter({'c': [5], 'b': [4], 'a': [3]})
>>> A.update(C)
>>> A
Counter({'c': [5], 'b': [4, 4], 'a': [3, 19]})
或者,如果这是一个难以解决的问题,因为你有很多计数器词典,你可以使用python3并尝试:
from collections import Counter
import collections
A = Counter({})
B = Counter({'a':[3], 'b':[4], 'c':[5]})
C = Counter({'a':[19], 'b':[4], 'c':[5] })
D = Counter({'a':[20]})
all_objects = vars()
all_object_keys = list(all_objects.keys())
for i in all_object_keys:
if i != 'A' and type(all_objects[i]) == collections.Counter:
A.update(all_objects[i])
print(A)
反击({&#39; a&#39;:[19,20,3],&#39; c&#39;:[5,5],&#39; b&#39;:[4, 4]})