Python collections.Counter 中所有计数的总和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18593519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:10:37  来源:igfitidea点击:

Sum of all counts in a collections.Counter

pythonpython-3.xcounter

提问by Baz

What is the best way of establishing the sum of all counts in a collections.Counterobject?

确定collections.Counter对象中所有计数总和的最佳方法是什么?

I've tried:

我试过了:

sum(Counter([1,2,3,4,5,1,2,1,6]))

sum(Counter([1,2,3,4,5,1,2,1,6]))

but this gives 21instead of 9?

但这给出了21而不是9

采纳答案by NPE

The code you have adds up the keys (i.e. the unique values in the list: 1+2+3+4+5+6=21).

您拥有的代码将键(即列表中的唯一值:)相加1+2+3+4+5+6=21

To add up the counts, use:

要将计数相加,请使用:

In [4]: sum(Counter([1,2,3,4,5,1,2,1,6]).values())
Out[4]: 9

This idiom is mentioned in the documentation, under "Common patterns".

文档中的“常见模式”下提到了这个习语。

回答by Martijn Pieters

Sum the values:

对值求和:

sum(some_counter.values())

Demo:

演示:

>>> from collections import Counter
>>> c = Counter([1,2,3,4,5,1,2,1,6])
>>> sum(c.values())
9

回答by martyn

sum(Counter([1,2,3,4,5,1,2,1,6]).values())