See below, why does the implementation of +=
blow away a key in my original counter?
>>> c = Counter({'a': 0, 'b': 0, 'c': 0})
>>> c.items()
[('a', 0), ('c', 0), ('b', 0)]
>>> c += Counter('abba')
>>> c.items()
[('a', 2), ('b', 2)]
I think that's impolite to say the least, there is quite a difference between "X was counted 0 times" and "we aren't even counting Xs". It seems like collections.Counter
is not a counter at all, it's more like a multiset.
But counters are a subclass of dict and we're allowed to construct them with zero or negative values: Counter(a=0, b=-1)
. If it's actually a "bag of things", wouldn't this be prohibited, restricting init to accept an iterable of hashable items?
To further confuse matters, counter implements update
and subtract
methods which have different behaviour to +
and -
operators. It seems like this class is having an identity crisis!
Is a Counter a dict or a bag?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…