开发者

Checking number of elements in Python's `Counter`

开发者 https://www.devze.com 2023-02-21 11:09 出处:网络
Python 2.7/3.1 introduced t开发者_如何学Gohe awesome collections.Counter. My question: How do I count how many \"element appearances\" a counter has?

Python 2.7/3.1 introduced t开发者_如何学Gohe awesome collections.Counter.

My question: How do I count how many "element appearances" a counter has?

I want this:

len(list(counter.elements()))

But shorter.


A more efficient solution is to sum up the counts (values) of each element:

sum(counter.values())

In Python 3.x, values() returns a view object of the dict's values.

In Python 2.x, values() returned an actual list. To avoid creating a new list with Python 2.x, use itervalues() instead:

sum(counter.itervalues())
0

精彩评论

暂无评论...
验证码 换一张
取 消