Summing the contents of two collections.Counter() objects [duplicate]

杀马特。学长 韩版系。学妹 提交于 2019-11-29 04:32:15

问题


This question already has an answer here:

  • Is there any pythonic way to combine two dicts (adding values for keys that appear in both)? 18 answers

I am working with collections.Counter() counters. I would like to combine two of them in a meaningful manner.

Suppose I have 2 counters, say,

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

and

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

I am trying to end up with:

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

How can I do this?


回答1:


All you need to do is add them:

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

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



来源:https://stackoverflow.com/questions/19356055/summing-the-contents-of-two-collections-counter-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!