I have a counter from the collections
module. What is the best way of summing all of the counts?
For example, I have:
my_counter = Counter({'a': 2, 'b': 2, 'c': 2, 'd': 1})
and would like to get the value 7
returned. As far as I can tell, the function sum
is for adding multiple counters together.
When you're counting the occurrences of a single object, you can use a single counter. However, when you need to count several different objects, you have to create as many counters as unique objects you have. To count several different objects at once, you can use a Python dictionary.
Python sum() Function The sum() function returns a number, the sum of all items in an iterable.
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.
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.
Since your question is about Python 2.7, you should use something like this
sum(my_counter.itervalues())
which on Python 3.x is effectively equivalent to
sum(my_counter.values())
In both cases you evaluate the sum lazily and avoid expensive intermediate data structures. Beware of using the Python 3.x variant on Py 2.x, because in the latter case my_counter.values()
calculates an entire list of counts and stores it in memory before calculating the sum.
>>> from collections import Counter
>>> sum(Counter({'a': 2, 'b': 2, 'c': 2, 'd': 1}).values())
7
Common patterns for working with Counter objects: sum(c.values())
# total of all counts
Source: https://docs.python.org/2/library/collections.html
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