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?
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) .
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.
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.
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.
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})
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