I am using a Counter
like this:
from collections import Counter
totals = Counter()
c_one = Counter(a=10, b=1)
c_two = Counter(a=10, b=-101)
totals += c_one
totals += c_two
# Output: Counter({'a': 20})
print(totals)
Which is not at all what I expected. I expected to see:
Counter({'a': 20, 'b': -100})
Where did my negatives go, and is there some Counter
that will let me use negatives?
In Python, positive numbers can be changed to negative numbers with the help of the in-built method provided in the Python library called abs (). When abs () is used, it converts negative numbers to positive. However, when -abs () is used, then a positive number can be changed to a negative number.
There are four basic data types in Python: 1. Numeric: These can be either integers or floats. Integers are positive or negative whole numbers without a decimal point.
Counter is a subclass of dict that's specially designed for counting hashable objects in Python. It's a dictionary that stores objects as keys and counts as values. To count with Counter , you typically provide a sequence or iterable of hashable objects as an argument to the class's constructor.
From the docs:
The multiset methods are designed only for use cases with positive values. The inputs may be negative or zero, but only outputs with positive values are created. There are no type restrictions, but the value type needs to support addition, subtraction, and comparison.
(emphasis added)
However, if you look a little closer you'll find your answer:
Elements are counted from an iterable or added-in from another mapping (or counter). Like dict.update() but adds counts instead of replacing them. Also, the iterable is expected to be a sequence of elements, not a sequence of (key, value) pairs.
(emphasis added)
All you have to do is make one tiny change, and your example will work:
from collections import Counter
totals = Counter()
c_one = Counter(a=10, b=1)
c_two = Counter(a=10, b=-101)
# Instead of totals += c_one; totals += c_two
totals.update(c_one)
totals.update(c_two)
# Output: Counter({'a': 20, 'b': -100})
print(totals)
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