如何添加或递增 Python 计数器 class 的单个项目

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

A 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 检查的逻辑(尤其是在笔记本中)。由于混乱,列表理解并不总是可取的等。

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

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

它使用 generator expression 而不是开放编码循环。

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

>>> 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 子类

好吧,你真的不需要使用 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