集合中所有计数的总和。 [英] Sum of all counts in a collections.Counter
本文介绍了集合中所有计数的总和。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 collection.Counter
对象中建立所有计数之和的最佳方法是什么?
What is the best way of establishing the sum of all counts in a collections.Counter
object?
我试过了:
sum(Counter([1,2,3,4,5,1,2,1,6]) )
但这会给出 21 而不是 9 ?
推荐答案
您所拥有的代码将键加起来(即列表中的唯一值: 1 + 2 + 3 + 4 + 5 + 6 = 21
)。
The code you have adds up the keys (i.e. the unique values in the list: 1+2+3+4+5+6=21
).
要累加计数,请使用:
In [4]: sum(Counter([1,2,3,4,5,1,2,1,6]).values())
Out[4]: 9
文档,在常用模式下。
这篇关于集合中所有计数的总和。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文