Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way of adding a set to a counter in Python

What is the most elegant way of incrementing a counter by 1 for each element in a set?

For example at the moment i do something like:

from collections import Counter
my_counter = Counter()
my_set = set(["a", "b", "c", "d"])
for item in my_set:
    my_counter[item] += 1

But i was wondering if it possible to 'add' a set to a already existing counter directly?

like image 948
kyrenia Avatar asked Oct 19 '16 17:10

kyrenia


People also ask

How do I turn a list into a counter in Python?

In Python, you can count the total number of elements in a list or tuple with the built-in function len() and the number of occurrences of an element with the count() method.

What is Most_common in Python?

most_common(n)This method returns the most common elements from the counter. If we don't provide value of 'n' then sorted dictionary is returned from most common the least common elements.


1 Answers

You could use the update method. update can accept an iterable (e.g. a set) or a mapping (e.g. a dict). Note that update adds to the count; it does not replace the count:

In [7]: my_counter.update(my_set)

In [8]: my_counter
Out[8]: Counter({'a': 1, 'b': 1, 'c': 1, 'd': 1})

Or, add another Counter in-place:

In [18]: my_counter += Counter(my_set)

In [19]: my_counter
Out[19]: Counter({'a': 2, 'b': 2, 'c': 2, 'd': 2})
like image 81
unutbu Avatar answered Sep 19 '22 01:09

unutbu