Update existing Counter with item frequencies from another list

Question:

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

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?

Asked By: JACKY88

||

Answers:

You can achieve that by:

count.update(b)
Answered By: Hussein Awala

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})
Answered By: AndrejH

It’s easy to just use again the Counter:

>>> Counter(b) + count     #  count is your original counter of list a

Counter({1: 4, 3: 4, 2: 3, 5: 1, 8: 1, 4: 1})
Answered By: Daniel Hao
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.