关于python:求和两个collections.counter()对象的内容

Summing the contents of two collections.Counter() objects

本问题已经有最佳答案,请猛点这里访问。

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

假设我有两个柜台,

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

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

我试图以以下方式结束:

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

我该怎么做?


您只需添加它们:

1
2
3
4
5
>>> 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})

来自文档:

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.