gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:45:46 24 4
gpt4 key购买 nike

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

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

关于Python合并两个计数器对象,保持最大的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40780232/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com