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

发布于 2021-01-29 15:20:02

Aset用于.update添加多个项目,并.add添加单个项目。

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

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

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

我可以Counter采取行动set(例如,不必将财产列入清单)吗?

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

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

我发现自己正在做很多事情,因为我正在制定各种has_some_property检查的逻辑(尤其是在笔记本中)。因此,列表理解并非总是可取的,等等。

关注者
0
被浏览
46
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看