本文介绍了当净值不正值时,将两个python字典组合成一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个python字典,我正在尝试将值合起来。答案在:最让我的方式。然而,我有一些情况下,净值可能是零或负,但我仍然希望最终的字典中的值。即使计数器将接受负值,它只会输出一个值,如果它大于零。



示例

  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
打印(C.items())

输出: code> [('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 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}
>>>
>>>对于set(a)| set(b)中的x,dict((x,a.get(x,0)+ b.get(x,0))
{'e':0,'a' :1,'f':-1,'d':5,'c':1,'b':5}


I have two python dictionaries that I'm trying to sum the values together on. The answer in: Is there any pythonic way to combine two dicts (adding values for keys that appear in both)? gets me most of the way. However I have cases where the net values may be zero or negative but I still want the values in the final dictionary. Even though Counters will accept negative values, it will only output a value if it's greater than zero.

Example

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())

Output: [('a', 1), ('c', 1), ('b', 5), ('d', 5)]

c = -3 + 4 = 1 is correct so the negative input is not an issue but e:0 and f:-1 are missing from the output

How can I perform the summation and get all values output?

解决方案

How about something like:

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

example:

>>> 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}

这篇关于当净值不正值时,将两个python字典组合成一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 00:40