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?
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.
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.
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})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With