Summing the contents of two collections.Counter() objects
本问题已经有最佳答案,请猛点这里访问。
我正在使用
假设我有两个柜台,
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.