繁体   English   中英

如何添加或增加 Python Counter 类的单个项目

[英]How to add or increment single item of the Python Counter class

set使用.update添加多个项目, .add添加一个。

为什么collections.Counter工作方式不同?

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

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

我可以让Counterset一样工作(即不必将属性放在列表中)?

用例: Counter非常好,因为它的defaultdict行为在稍后检查时为丢失的键提供默认零:

>>> c = Counter()
>>> c['i']
0

我发现自己经常这样做,因为我正在为各种has_some_property检查(尤其是在笔记本中)制定逻辑。 由于它的混乱,列表理解并不总是可取的等。

好吧,你真的不需要使用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
>>> c = collections.Counter(a=23, b=-9)

您可以添加一个新元素并设置其值,如下所示:

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

增量:

>>> c['d'] += 1
>>> c
Counter({'a': 23, 'd': 9, 'b': -9} 

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

>>> c['b'] = 0
>>> c
Counter({'a': 23, 'd': 9, 'b': 0})

要删除使用del

>>> del c['b']
>>> c
Counter({'a': 23, 'd': 9})

Counter 是一个 dict 子类

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

c = Counter(item.property for item in something if item.has_some_property)

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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