Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum all values of a counter in Python 2 [duplicate]

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.

like image 513
kyrenia Avatar asked Sep 10 '15 20:09

kyrenia


People also ask

Can you add counters together python?

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.

What is sum() sum() in Python?

Python sum() Function The sum() function returns a number, the sum of all items in an iterable.

How do you sum a count in python?

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.

What does counter () do in Python?

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.


2 Answers

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.

like image 179
3 revs Avatar answered Nov 04 '22 16:11

3 revs


>>> 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

like image 38
Joe Young Avatar answered Nov 04 '22 17:11

Joe Young