Pythonic way to iterate over a collections.Counter() instance in descending order?(以降序遍历 collections.Counter() 实例的 Pythonic 方式?)
问题描述
在 Python 2.7 中,我想以递减计数顺序迭代 collections.Counter 实例.
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
在上面的示例中,元素似乎按照它们添加到 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() 以按所需顺序获取项目.另请参阅 Counter.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)]
这篇关于以降序遍历 collections.Counter() 实例的 Pythonic 方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:以降序遍历 collections.Counter() 实例的 Pythonic 方式?
基础教程推荐
- Kivy 使用 opencv.调整图像大小 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
