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 方式?


基础教程推荐
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 筛选NumPy数组 2022-01-01