以降序遍历 collections.Counter() 实例的 Pythonic 方式?

Pythonic way to iterate over a collections.Counter() instance in descending order?(以降序遍历 collections.Counter() 实例的 Pythonic 方式?)
本文介绍了以降序遍历 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 方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)