【问题标题】:Is there a Counter in Python that can accumulate negative values? [duplicate]Python中是否有可以累积负值的计数器? [复制]
【发布时间】:2015-05-28 12:10:50
【问题描述】:

我正在使用这样的Counter

from collections import Counter

totals = Counter()
c_one = Counter(a=10, b=1)
c_two = Counter(a=10, b=-101)

totals += c_one
totals += c_two    

# Output: Counter({'a': 20})
print(totals)

这完全不是我所期望的。我希望看到:

Counter({'a': 20, 'b': -100})

我的底片去哪儿了,有没有一些Counter 可以让我使用底片?

【问题讨论】:

  • 我很好奇。问一个问题,然后发布一个答案作为其他人(即“来自您链接的文档”)是什么意思。 同时 ?
  • @SiHa 我想这有点奇怪。

标签: python counter


【解决方案1】:

来自the docs

多重集方法仅适用于具有正值的用例。输入可能是负数或零,但只创建具有正值的输出。没有类型限制,但是值类型需要支持加减比较。

(强调)

但是,如果您仔细观察,您会发现your answer

元素是从另一个映射(或计数器)的可迭代或附加元素中计算出来的。 与 dict.update() 类似,但添加计数而不是替换它们。 此外,iterable 应为元素序列,而不是(键、值)对序列。

(强调)

你所要做的就是做一个微小的改变,你的例子就会奏效:

from collections import Counter

totals = Counter()
c_one = Counter(a=10, b=1)
c_two = Counter(a=10, b=-101)

# Instead of totals += c_one; totals += c_two
totals.update(c_one)
totals.update(c_two)    

# Output: Counter({'a': 20, 'b': -100})
print(totals)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-18
    • 2021-09-03
    • 2012-04-19
    • 2013-06-19
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    相关资源
    最近更新 更多