如何按值对Counter排序? - Python [英] How to sort Counter by value? - python
问题描述
除了进行反向列表理解的列表理解之外,还有一种Python的方法可以按值对Counter进行排序吗?如果是这样,它比这快:
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)
推荐答案
使用它将以最有效的方式进行;如果您要求输入前N个而不是所有值,则使用heapq
而不是直接排序:
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)]
除计数器外,始终可以根据key
函数来调整排序. .sort()
和sorted()
都可调用,可用于指定对输入序列进行排序的值. sorted(x, key=x.get, reverse=True)
将为您提供与x.most_common()
相同的排序,但是仅返回键,例如:
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']
或者您可以仅对给定的(key, value)
对值进行排序:
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)]
有关更多信息,请参见 Python排序方法.
See the Python sorting howto for more information.
这篇关于如何按值对Counter排序? - Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!