Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

counter

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?

like image 788
tumultous_rooster Avatar asked Oct 14 '13 08:10

tumultous_rooster


People also ask

What does Counter() do in Python?

Counter is a subclass of dict that's specially designed for counting hashable objects in Python. It's a dictionary that stores objects as keys and counts as values. To count with Counter , you typically provide a sequence or iterable of hashable objects as an argument to the class's constructor.

What does counter from collections do in Python?

A Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts.

How do you sum a count in python?

Use a formula sum = sum + current number . At last, after the loop ends, calculate the average using a formula average = sum / n . Here, The n is a number entered by the user.


1 Answers

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.

Note that if you want to save memory by modifying the Counter in-place rather than creating a new one, you can do a.update(b) or b.update(a).

like image 56
TerryA Avatar answered Oct 06 '22 01:10

TerryA