如何添加或增加Python Counter类的单个项目 [英] How to add or increment single item of the Python Counter class

查看:63
本文介绍了如何添加或增加Python Counter类的单个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个集合使用 .update 添加多个项目,并使用 .add 添加一个。

A set uses .update to add multiple items, and .add to add a single one.

为什么不 collections.Counter 是否以相同的方式工作?

Why doesn't collections.Counter work the same way?

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

To increment a single Counter item using Counter.update, you have to add it to a list:

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

我可以得到计数器就像 set 一样(即消除了将属性放入列表中的行为)?

Can I get Counter to act like set (i.e. eliminate having to put the property in a list)?

用例: C nter 非常好,因为其类似 defaultdict 的行为,即在以后检查时为丢失的密钥提供默认的零:

Use case: Counter is very nice because of its defaultdict-like behavior of providing a default zero for missing keys when checking later:

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

我发现自己正在做很多事情,各种 has_some_property 检查的逻辑(尤其是在笔记本中)。因此,列表理解并不总是那么理想。

I find myself doing this a lot as I'm working out the logic for various has_some_property checks (especially in a notebook). Because of the messiness of that, a list comprehension isn't always desirable etc.

推荐答案

嗯,您并不需要使用 Counter 的方法进行计数,对吗?有一个 + = 运算符,它也可以与Counter一起使用。

Well, you don't really need to use methods of Counter in order to count, do you? There's a += operator for that, which also works in conjunction with 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

这篇关于如何添加或增加Python Counter类的单个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆