Python中是否有可以累加负值的Counter?

Is there a Counter in Python that can accumulate negative values?

我正在使用这样的 Counter

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)

这完全出乎我的意料。我希望看到:

Counter({'a': 20, 'b': -100})

我的底片哪里去了,有没有一些Counter可以让我使用底片?

来自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.

(强调)

然而,如果你仔细观察,你会发现 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.

(强调)

您只需做一个微小的改变,您的示例就会起作用:

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)