Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summing list of counters in python

I am looking to sum a list of counters in python. For example to sum:

counter_list = [Counter({"a":1, "b":2}), Counter({"b":3, "c":4})] 

to give Counter({'b': 5, 'c': 4, 'a': 1})

I can get the following code to do the summation:

counter_master = Counter() for element in counter_list:     counter_master = counter_master + element 

But I am confused as to why counter_master = sum(counter_list) results in the error TypeError: unsupported operand type(s) for +: 'int' and 'Counter' ? Given it is possible to add counters together, why is it not possible to sum them?

like image 392
kyrenia Avatar asked May 02 '15 14:05

kyrenia


People also ask

Can you add counters together Python?

Addition and subtraction combine counters by adding or subtracting the counts of corresponding elements. Note that if you want to save memory by modifying the Counter in-place rather than creating a new one, you can do a. update(b) or b. update(a) .

How do you show a Counter list in Python?

Accessing Elements in Python Counter To get the list of elements in the counter we can use the elements() method. It returns an iterator object for the values in the Counter.

How do you sum a count in Python?

Python provides an inbuilt function sum() which sums up the numbers in the list. Syntax: sum(iterable, start) iterable : iterable can be anything list , tuples or dictionaries , but most importantly it should be numbers. start : this start is added to the sum of numbers in the iterable.

How do you use counters in Python?

Using the Python Counter tool, you can count the key-value pairs in an object, also called a hashtable object. The Counter holds the data in an unordered collection, just like hashtable objects. The elements here represent the keys and the count as values. It allows you to count the items in an iterable list.


1 Answers

The sum function has the optional start argument which defaults to 0. Quoting the linked page:

sum(iterable[, start])

Sums start and the items of an iterable from left to right and returns the total

Set start to (empty) Counter object to avoid the TypeError:

In [5]: sum(counter_list, Counter()) Out[5]: Counter({'b': 5, 'c': 4, 'a': 1}) 
like image 183
vaultah Avatar answered Sep 22 '22 06:09

vaultah