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

2024-04-26 10:50:50 发布

您现在位置:Python中文网/ 问答频道 /正文

Aset使用.update添加多个项,使用.add添加单个项。为什么^{}的工作方式不一样?

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

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

我能让Counterset那样工作吗(也就是说,不必把属性放在列表中)?

编辑:用例:想象一个你有一些未知对象的用例,你正在快速尝试许多不同的东西来发现它们的一些初步的东西:性能和伸缩性无关紧要,理解会使加和减逻辑耗时。


Tags: inadd列表for方式counterupdateproperty
3条回答
>>> 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子类

有一种更像Python的方法可以做你想做的事:

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

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

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

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

相关问题 更多 >