gpt4 book ai didi

python - 将两个 collections.Counter() 对象的内容相加

转载 作者:IT老高 更新时间:2023-10-28 21:37:36 29 4
gpt4 key购买 nike

我正在使用 collections.Counter() 计数器。我想以一种有意义的方式将其中两个结合起来。

假设我有 2 个计数器,比如说,

Counter({'menu': 20, 'good': 15, 'happy': 10, 'bar': 5})

Counter({'menu': 1, 'good': 1, 'bar': 3})

我想最终得到:

Counter({'menu': 21, 'good': 16, 'happy': 10,'bar': 8})

我该怎么做?

最佳答案

您需要做的就是添加它们:

>>> from collections import Counter
>>> a = Counter({'menu': 20, 'good': 15, 'happy': 10, 'bar': 5})
>>> b = Counter({'menu': 1, 'good': 1, 'bar': 3})
>>> a + b
Counter({'menu': 21, 'good': 16, 'happy': 10, 'bar': 8})

来自 docs :

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.

请注意,如果您想通过就地修改 Counter 而不是创建新的来节省内存,您可以执行 a.update(b)b.update(a).

关于python - 将两个 collections.Counter() 对象的内容相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19356055/

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