本文介绍了Pythonic方法以递减的顺序迭代collections.Counter()实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 2(2.7,更准确地说)中,我想以递减计数顺序迭代collections.Counter实例。

In Python 2 (2.7, to be more precise), 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

在上面的示例,似乎元素按照它们添加到Counter实例的顺序进行迭代。

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

我想从最高到最低迭代列表。我看到Counter的字符串表示就是这样,只是想知道是否有推荐的方法来做它。

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.

推荐答案

你可以迭代超过 c.most_common()以获得所需订单的商品。另请参阅。

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

示例:

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

这篇关于Pythonic方法以递减的顺序迭代collections.Counter()实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 12:06
查看更多