Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Update existing Counter with item frequencies from another list

I learned that if there is a single list, collections.Counter can generate the frequency table of all elements in the list.

Now I have a function whose return value is a list. This function needs to be run many times, and I need to have the frequency of elements from all these lists.

For example, suppose I have

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

a = [1, 2, 3, 1, 2, 3, 4]
count = collections.Counter(a)

from the first run and I get

Counter({1: 2, 2: 2, 3: 2, 4: 1})

How do I update the counter once the second run’s return b = [1, 3, 5, 8, 2, 1, 3] becomes available?

>Solution :

You can call the method collections.Counter.update([iterable-or-mapping]) to update the values (add the counts) of the existing Counter object.

Elements are counted from an iterable or added-in from another mapping (or counter). Like dict.update() but adds counts instead of
replacing them. Also, the iterable is expected to be a sequence of
elements, not a sequence of (key, value) pairs.

Example of updating an existing Counter object.

>>> from collections import Counter
>>> list_a = ["a", "b", "c", "c", "d"]
>>> counter = Counter(list_a)
>>> print(counter)
Counter({'c': 2, 'a': 1, 'b': 1, 'd': 1})
>>> list_b = ["b", "b", "c", "e", "f"]
>>> counter.update(list_b)
>>> print(counter)
Counter({'b': 3, 'c': 3, 'a': 1, 'd': 1, 'e': 1, 'f': 1})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading