简体   繁体   中英

Python adding Counter objects with negative numbers fails

why do adding an empty counter to another with a negative value results in 0

from collections import Counter
a=Counter({'a':-1})
b=Counter()
print(a+b)

Result

Counter()

but if the counter added to the empty one has a positive value it works

Because when you add counters together, any entry in the result with a total of zero or less is omitted by definition in the docs.

Here are the docs: https://docs.python.org/3/library/collections.html#collections.Counter:~:text=Several%20mathematical%20operations,zero%20or%20less .

So that this answer is self-contained, the docs read:

Several mathematical operations are provided for combining Counter objects to produce multisets (counters that have counts greater than zero). Addition and subtraction combine counters by adding or subtracting the counts of corresponding elements. Intersection and union return the minimum and maximum of corresponding counts. Equality and inclusion compare corresponding counts. Each operation can accept inputs with signed counts, but the output will exclude results with counts of zero or less.

Counter filters out the keys which have counts of zero or less. See the docs :

Each operation can accept inputs with signed counts, but the output will exclude results with counts of zero or less.

However, the update method does preserve the mentioned values.

from collections import Counter


a = Counter({'a':-1})
b = Counter()
a.update(b)

print(a) # Counter({'a': -1})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM