Python Counter类:添加或增加单个项目

msc*_*arf 20 python counter

一个set使用.update添加多个项目,并.add添加一个.为什么不collections.Counter以同样的方式工作?

要使用增加单个Counter项目Counter.update,您必须将其添加到列表中:

c = Counter()

for item in something:
    for property in properties_of_interest:
        if item.has_some_property: # pseudocode: more complex logic here
            c.update([item.property])
        elif item.has_some_other_property:
            c.update([item.other_property])
        # elif... etc
Run Code Online (Sandbox Code Playgroud)

我可以Counter采取行动set(即消除必须将财产列入清单)?

编辑:使用案例:想象一下你有一些未知对象的情况,并且你正在快速尝试许多不同的事情来找出关于它们的一些初步事项:性能和缩放无关紧要,并且理解会增加和减少逻辑耗时的.

shx*_*hx2 20

好吧,你真的不需要使用方法Counter来计算,对吗?有一个+=操作员,也可以与Counter一起使用.

c = Counter()
for item in something:
    if item.has_some_property:
        c[item.property] += 1
    elif item.has_some_other_property:
        c[item.other_property] += 1
    elif item.has_some.third_property:
        c[item.third_property] += 1
Run Code Online (Sandbox Code Playgroud)

  • 起初对我来说并不明显的是,即使计数器中尚不存在您要递增的密钥,它也能正常工作。 (4认同)

Vid*_*a G 11

>>> c = collections.Counter(a=23, b=-9)
Run Code Online (Sandbox Code Playgroud)

您可以添加新元素并将其值设置为:

>>> c['d'] = 8
>>> c
Counter({'a': 23, 'd': 8, 'b': -9})
Run Code Online (Sandbox Code Playgroud)

增量:

>>> c['d'] += 1
>>> c
Counter({'a': 23, 'd': 9, 'b': -9} 
Run Code Online (Sandbox Code Playgroud)

请注意,c['b'] = 0但不删除:

>>> c['b'] = 0
>>> c
Counter({'a': 23, 'd': 9, 'b': 0})
Run Code Online (Sandbox Code Playgroud)

要删除使用del:

>>> del c['b']
>>> c
Counter({'a': 23, 'd': 9})
Run Code Online (Sandbox Code Playgroud)

Counter是一个dict子类


Chr*_*ger 5

有一种更 Pythonic 的方式来做你想做的事:

c = Counter(item.property for item in something if item.has_some_property)
Run Code Online (Sandbox Code Playgroud)

它使用生成器表达式而不是对循环进行开放编码。

编辑:错过了您的无列表理解段落。我仍然认为这是Counter在实践中实际使用的方法。如果您有太多代码要放入生成器表达式或列表推导式中,通常最好将其分解为函数并从推导式中调用。