如何添加或增加Python Counter类的单个项目
Aset
用于.update
添加多个项目,并.add
添加单个项目。
为什么不collections.Counter
以相同的方式工作?
要Counter
使用来增加单个项目Counter.update
,您必须将其添加到列表中:
from collections import Counter
c = Counter()
for item in something:
for property in properties_of_interest:
if item.has_some_property: # simplified: more complex logic here
c.update([item.property])
elif item.has_some_other_property:
c.update([item.other_property])
# elif... etc
我可以Counter
采取行动set
(例如,不必将财产列入清单)吗?
用例:Counter
非常好,因为它defaultdict
的行为类似于在以后检查时为丢失的键提供默认零:
>>> c = Counter()
>>> c['i']
0
我发现自己正在做很多事情,因为我正在制定各种has_some_property
检查的逻辑(尤其是在笔记本中)。因此,列表理解并非总是可取的,等等。