如何按值对计数器进行排序?- Python [英] How to sort Counter by value? - python

查看:34
本文介绍了如何按值对计数器进行排序?- Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了做反向列表理解的列表理解之外,有没有一种pythonic方法来按值对计数器进行排序?如果是这样,它会比这更快:

<预><代码>>>>从集合导入计数器>>>x = 计数器({'a':5, 'b':3, 'c':7})>>>排序(x)['a', 'b', 'c']>>>排序(x.items())[('a', 5), ('b', 3), ('c', 7)]>>>[(l,k) for k,l in sorted([(j,i) for i,j in x.items()])][('b', 3), ('a', 5), ('c', 7)]>>>[(l,k) for k,l in sorted([(j,i) for i,j in x.items()], reverse=True)][('c', 7), ('a', 5), ('b', 3)

解决方案

使用 Counter.most_common() 方法,它会为你排序:

<预><代码>>>>从集合导入计数器>>>x = 计数器({'a':5, 'b':3, 'c':7})>>>x.most_common()[('c', 7), ('a', 5), ('b', 3)]

它会以最有效的方式进行;如果您要求 Top N 而不是所有值,则使用 heapq 而不是直接排序:

<预><代码>>>>x.most_common(1)[('c', 7)]

在计数器之外,总是可以根据key函数调整排序;.sort()sorted() 都可以调用,它允许你指定一个值来对输入序列进行排序;sorted(x, key=x.get, reverse=True) 会给你与 x.most_common() 相同的排序,但只返回键,例如:

<预><代码>>>>排序(x,key=x.get,reverse=True)['出租车']

或者你可以只对给定的值进行排序 (key, value) 对:

<预><代码>>>>排序(x.items(),key=lambda 对:pair[1],reverse=True)[('c', 7), ('a', 5), ('b', 3)]

有关详细信息,请参阅 Python 排序方法.

Other than doing list comprehensions of reversed list comprehension, is there a pythonic way to sort Counter by value? If so, it is faster than this:

>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})
>>> sorted(x)
['a', 'b', 'c']
>>> sorted(x.items())
[('a', 5), ('b', 3), ('c', 7)]
>>> [(l,k) for k,l in sorted([(j,i) for i,j in x.items()])]
[('b', 3), ('a', 5), ('c', 7)]
>>> [(l,k) for k,l in sorted([(j,i) for i,j in x.items()], reverse=True)]
[('c', 7), ('a', 5), ('b', 3)

解决方案

Use the Counter.most_common() method, it'll sort the items for you:

>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})
>>> x.most_common()
[('c', 7), ('a', 5), ('b', 3)]

It'll do so in the most efficient manner possible; if you ask for a Top N instead of all values, a heapq is used instead of a straight sort:

>>> x.most_common(1)
[('c', 7)]

Outside of counters, sorting can always be adjusted based on a key function; .sort() and sorted() both take callable that lets you specify a value on which to sort the input sequence; sorted(x, key=x.get, reverse=True) would give you the same sorting as x.most_common(), but only return the keys, for example:

>>> sorted(x, key=x.get, reverse=True)
['c', 'a', 'b']

or you can sort on only the value given (key, value) pairs:

>>> sorted(x.items(), key=lambda pair: pair[1], reverse=True)
[('c', 7), ('a', 5), ('b', 3)]

See the Python sorting howto for more information.

这篇关于如何按值对计数器进行排序?- Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆