Python合并两个计数器对象,保持最大的总和

时间:2016-11-24 07:24:21

标签: python counter

如果我有两个计数器对象,我想合并它们,从一个添加新值,如果两个计数器包含相同的值,则保持最大计数。

Counter a = { "apple":3, "peach":1, "pears":7, "watermelon":2, "grapes":7 }

Counter b = { "apple":12, "kiwi":9, "grapes":2, "pears":21, "pineapple":2, "oranges":2 }

#desired output
counter c = { "apple":12, "pears":21, "grapes":7 "peach":1, "watermelon":2, "pineapple":2, "oranges":2} 

目前我已经尝试更新计数器,但这似乎合并了两个计数器,但总结了他们的计数。我只想合并计数器并保持最大值,或者如果没有计数器则添加到计数器。

3 个答案:

答案 0 :(得分:2)

你可以使用内置的Counter从每个a&b中获取不同的键,并使用它们来获得所需的最大逻辑:

Counter({key:max(a[key], b[key]) for key in a&b})

以下是一个示例运行:

>>> from collections import Counter
>>> a=Counter({ "apple":3, "peach":1, "pears":7, "watermelon":2, "grapes":7 })
>>> b=Counter({ "apple":12, "kiwi":9, "grapes":2, "pears":21, "pineapple":2, "oranges":2 })
>>> Counter({key:max(a[key], b[key]) for key in a&b})
Counter({'pears': 21, 'apple': 12, 'grapes': 7})
>>> 

请注意,如果您想要使用此结构在python中构建的公共元素的最小值:

>>> a&b
Counter({'pears': 7, 'apple': 3, 'grapes': 2})
>>> 

答案 1 :(得分:2)

您可以使用两个计数器中的键的交集,并在使用max获得最大值时使用dict理解进行迭代:

>>> a = Counter({ "apple":3, "peach":1, "pears":7, "watermelon":2, "grapes":7 })
>>> b = Counter({ "apple":12, "kiwi":9, "grapes":2, "pears":21, "pineapple":2, "oranges":2 })
>>> Counter({k: max(a[k], b[k]) for k in a.keys() & b.keys()})
Counter({'pears': 21, 'apple': 12, 'grapes': 7})

请注意,上述内容仅适用于Python 3,在Python 2上,您需要调用viewkeys代替:

>>> Counter({k: max(a[k], b[k]) for k in a.viewkeys() & b.viewkeys()})
Counter({'pears': 21, 'apple': 12, 'grapes': 7})

答案 2 :(得分:1)

在OP编辑问题后,只需使用按位或('|')运算符即可实现所需的输出:

from collections import Counter

a = Counter({ "apple":3, "peach":1, "pears":7, "watermelon":2, "grapes":7 })

b = Counter({ "apple":12, "kiwi":9, "grapes":2, "pears":21, "pineapple":2, "oranges":2 })

c = a | b

print(c)
>> Counter({'pears': 21, 'apple': 12, 'kiwi': 9, 'grapes': 7, 'watermelon': 2, 'oranges': 2,
            'pineapple': 2, 'peach': 1})