当净值不为正时,将两个 python 字典合二为一

combining two python dictionaries into one when the net values are not positive

我有两个 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 缺失

如何执行求和并输出所有值?

怎么样:

dict((x, a.get(x, 0) + b.get(x, 0)) for x in set(a)|set(b))

示例:

>>> a = {'a':1, 'b':2, 'c':-3, 'e':5, 'f': 5}
>>> b = {'b':3, 'c':4, 'd':5, 'e':-5, 'f': -6}
>>>
>>> dict((x, a.get(x, 0) + b.get(x, 0)) for x in set(a)|set(b))
{'e': 0, 'a': 1, 'f': -1, 'd': 5, 'c': 1, 'b': 5}

求和会降低 0 和更低的值,是的,如文档所述:

Several mathematical operations are provided for combining Counter objects to produce multisets (counters that have counts greater than zero). Addition and subtraction combine counters by adding or subtracting the counts of corresponding elements. Intersection and union return the minimum and maximum of corresponding counts. Each operation can accept inputs with signed counts, but the output will exclude results with counts of zero or less.

[...]

  • The multiset methods are designed only for use cases with positive values. The inputs may be negative or zero, but only outputs with positive values are created. There are no type restrictions, but the value type needs to support addition, subtraction, and comparison.

如果您想将值保留为 0 或更低,则需要使用 Counter.update()。由于这是就地操作,您必须在此处创建一个副本:

>>> 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.copy()
>>> C.update(B)
>>> C
Counter({'b': 5, 'd': 5, 'a': 1, 'c': 1, 'e': 0, 'f': -1})

如果保留 A 不是目标,您可以直接更新它。