请看下面,为什么+=
的实现会吹走我原来计数器中的一个键?在
>>> 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)]
我认为这至少是不礼貌的,在“X被数了0次”和“我们甚至没有计算X”之间有很大的区别。似乎collections.Counter
根本不是一个计数器,它更像是一个多集。在
但是计数器是dict的一个子类,我们可以用零或负值构造它们:Counter(a=0, b=-1)
。如果它实际上是一个“一包东西”,这不是被禁止的,限制init接受一个可散列项的iterable吗?在
为了进一步混淆问题,counter实现了update
和{+
和{
计数器是dict还是bag?
从source
计数器的实现似乎是删除和为零的非正键的
键。由于默认值为零,并且源代码也为零,因此生成的dict不包含该键。也许你可以用update得到同样的行为:
^{pr2}$好像做了你想做的事。可能速度较慢,手工实现
__add__
方法会快得多。Counter
s是一种多集。从^{强调我的。
更进一步,它告诉您有关
Counter
s的多集性质的更多细节:因此
Counter
对象是同时是;字典和包。然而,标准字典不支持加法,但是Counter
s支持加法,因此Counter
s并没有破坏字典在这里设置的优先级。如果要保留零,请使用
Counter.update()
并传入另一个对象的Counter.elements()
的结果:演示:
^{pr2}$相关问题 更多 >
编程相关推荐