如何按值对计数器进行排序?- Python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20950650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:37:27  来源:igfitidea点击:

How to sort Counter by value? - python

pythonsortingcollectionscounter

提问by alvas

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:

除了对反向列表理解进行列表理解之外,是否有一种 Pythonic 方法可以按值对 Counter 进行排序?如果是这样,它比这更快:

>>> 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)

采纳答案by Martijn Pieters

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

使用该Counter.most_common()方法,它会为您排序项目:

>>> 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 heapqis used instead of a straight sort:

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

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

Outside of counters, sorting can always be adjusted based on a keyfunction; .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:

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

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

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

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

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

See the Python sorting howtofor more information.

有关更多信息,请参阅Python 排序方法

回答by Inbar Rose

Yes:

是的:

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

Using the sorted keyword key and a lambda function:

使用 sorted 关键字 key 和 lambda 函数:

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

This works for all dictionaries. However Counterhas a special function which already gives you the sorted items (from most frequent, to least frequent). It's called most_common():

这适用于所有词典。但是Counter有一个特殊的功能,它已经给你排序的项目(从最频繁到最不频繁)。它被称为most_common()

>>> x.most_common()
[('c', 7), ('a', 5), ('b', 3)]
>>> list(reversed(x.most_common()))  # in order of least to most
[('b', 3), ('a', 5), ('c', 7)]

You can also specify how many items you want to see:

您还可以指定要查看的项目数量:

>>> x.most_common(2)  # specify number you want
[('c', 7), ('a', 5)]

回答by Hooked

A rather nice addition to @MartijnPietersanswer is to get back a dictionarysorted by occurrence since Collections.most_commononly returns a tuple. I often couple this with a json output for handy log files:

@MartijnPieters答案的一个相当不错的补充是取回按出现次数排序的字典,因为Collections.most_common只返回一个元组。我经常将它与方便的日志文件的 json 输出结合起来:

from collections import Counter, OrderedDict

x = Counter({'a':5, 'b':3, 'c':7})
y = OrderedDict(x.most_common())

With the output:

随着输出:

OrderedDict([('c', 7), ('a', 5), ('b', 3)])
{
  "c": 7, 
  "a": 5, 
  "b": 3
}

回答by Alex Seam

More general sorted, where the keykeyword defines the sorting method, minus before numerical type indicates descending:

更一般的sorted,其中key关键字定义了排序方式,数字类型前减号表示降序:

>>> x = Counter({'a':5, 'b':3, 'c':7})
>>> sorted(x.items(), key=lambda k: -k[1])  # Ascending
[('c', 7), ('a', 5), ('b', 3)]