Answer a question

In Python 2.7, I want to iterate over a collections.Counter instance in descending count order.

>>> import collections
>>> c = collections.Counter()
>>> c['a'] = 1
>>> c['b'] = 999
>>> c
Counter({'b': 999, 'a': 1})
>>> for x in c:
        print x
a
b

In the example above, it appears that the elements are iterated in the order they were added to the Counter instance.

I'd like to iterate over the list from highest to lowest. I see that the string representation of Counter does this, just wondering if there's a recommended way to do it.

Answers

You can iterate over c.most_common() to get the items in the desired order. See also the documentation of Counter.most_common().

Example:

>>> c = collections.Counter(a=1, b=999)
>>> c.most_common()
[('b', 999), ('a', 1)]
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐