对两个collections.Counter()对象的内容求和

2024-04-25 22:32:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用collections.Counter()计数器。我想以一种有意义的方式把它们结合起来。

假设我有两个柜台

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

我该怎么做?


Tags: 方式counter计数器barcollectionsmenu意义good
1条回答
网友
1楼 · 发布于 2024-04-25 22:32:38

您只需添加它们:

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

相关问题 更多 >