Skip to main content
 首页 » 编程设计

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

2025年05月04日26pengyingh

如果我有两个计数器对象并且我想合并它们,从一个中添加新值并在两个计数器包含相同值时保留最大计数。

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}  

目前我已经尝试更新计数器,但这似乎合并了两个计数器,但对它们的计数求和。我只想合并计数器并保留最大值或添加到计数器(如果还没有)。

请您参考如下方法:

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