gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:17:33 26 4
gpt4 key购买 nike

一个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

关于python - 如何添加或增加 Python Counter 类的单个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30001856/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com