2024-04-25 22:32:38 发布
网友
我正在使用collections.Counter()计数器。我想以一种有意义的方式把它们结合起来。
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})
我该怎么做?
您只需添加它们:
>>> 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.
您只需添加它们:
从docs:
相关问题 更多 >
编程相关推荐