gpt4 book ai didi

python - 添加计数器删除键

转载 作者:太空狗 更新时间:2023-10-29 17:43:19 25 4
gpt4 key购买 nike

见下文,为什么 += 的实现会在我原来的计数器中吹掉一个键?

>>> c = Counter({'a': 0, 'b': 0, 'c': 0})
>>> c.items()
[('a', 0), ('c', 0), ('b', 0)]
>>> c += Counter('abba')
>>> c.items()
[('a', 2), ('b', 2)]

我认为这至少可以说是不礼貌的,“X 被计算为 0 次”和“我们甚至没有计算 Xs”之间是有很大区别的。看起来 collections.Counter 根本不是一个计数器,它更像是一个 multiset。

但是计数器是字典的子类,我们可以用零值或负值构造它们:Counter(a=0, b=-1)。如果它实际上是一个“东西袋”,这不会被禁止,限制 init 接受可哈希项目的迭代吗?

为了进一步混淆问题,counter 实现了 updatesubtract 方法,它们与 +- 有不同的行为运营商。看来这个类(class)有身份危机了!

Counter 是 dict 还是 bag?

最佳答案

计数器一种多重集。来自Counter() documentation :

Several mathematical operations are provided for combining Counter objects to produce multisets (counters that have counts greater than zero). Addition and subtraction combine counters by adding or subtracting the counts of corresponding elements. Intersection and union return the minimum and maximum of corresponding counts. Each operation can accept inputs with signed counts, but the output will exclude results with counts of zero or less.

强调我的。

进一步,它告诉您为您提供有关 Counter 的多重集性质的更多详细信息:

Note: Counters were primarily designed to work with positive integers to represent running counts; however, care was taken to not unnecessarily preclude use cases needing other types or negative values. To help with those use cases, this section documents the minimum range and type restrictions.

[...]

  • The multiset methods are designed only for use cases with positive values. The inputs may be negative or zero, but only outputs with positive values are created. There are no type restrictions, but the value type needs to support addition, subtraction, and comparison.

所以 Counter 对象是两者;字典 包。然而,标准词典不支持加法,但 Counter 支持,所以这并不是说 Counter 打破了此处词典设置的优先级。

如果您想保留零,请使用 Counter.update() 并传入另一个对象的 Counter.elements() 的结果:

c.update(Counter('abba').elements())

演示:

>>> c = Counter({'a': 0, 'b': 0, 'c': 0})
>>> c.update(Counter('abba').elements())
>>> c
Counter({'a': 2, 'b': 2, 'c': 0})

关于python - 添加计数器删除键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21887125/

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