【发布时间】:2015-07-12 04:04:33
【问题描述】:
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
我可以让Counter 像set 一样行事(即无需将属性放在列表中)吗?
用例:Counter 非常好,因为它具有类似于defaultdict 的行为,即在稍后检查时为丢失的键提供默认零:
>>> c = Counter()
>>> c['i']
0
我发现自己经常这样做,因为我正在研究各种has_some_property 检查的逻辑(尤其是在笔记本中)。由于那样的混乱,列表理解并不总是可取的等等。
【问题讨论】:
-
那么你的代码和
Counter.update有什么问题? -
我必须把它贴在假名单上。没什么大不了的;我只是想知道没有
add背后是否有想法。 -
update方法接受一个可迭代的 aas 参数,并且该可迭代对象应该是一个元素序列,而不是一个(键、值)对序列。 -
就像我在评论中所说的那样 -
add甚至如何帮助你 - 你正在选择要添加的 what... 我没看到重点 - 你能举例说明.add的工作原理吗? -
has_some_property与仅仅获取属性本身有不同的逻辑吗? - 另请注意 - 使用当前的helper,您可能会将None结果放入您的Counter- 这可能是可取的,也可能不是......