【发布时间】:2015-04-23 03:42:33
【问题描述】:
我有两个 python 字典,我试图将这些值加在一起。答案在:Is there any pythonic way to combine two dicts (adding values for keys that appear in both)? 让我大部分时间。但是,在某些情况下,净值可能为零或负,但我仍然想要最终字典中的值。尽管 Counters 会接受负值,但它只会在大于零时输出一个值。
例子
from collections import Counter
A = Counter({'a': 1, 'b': 2, 'c': -3, 'e': 5, 'f': 5})
B = Counter({'b': 3, 'c': 4, 'd': 5, 'e': -5, 'f': -6})
C = A + B
print(C.items())
输出:[('a', 1), ('c', 1), ('b', 5), ('d', 5)]
c = -3 + 4 = 1 是正确的,因此负输入不是问题,但输出中缺少 e:0 和 f:-1
如何执行求和并获得所有值输出?
【问题讨论】:
-
你需要一个循环遍历唯一的排序组合键
标签: python dictionary