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

alv*_*vas 107 python sorting collections counter

除了对反向列表理解进行列表理解之外,还有一种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)
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 198

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

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

它会以最有效的方式这样做; 如果您要求使用前N而不是所有值,heapq则使用a而不是直接排序:

>>> x.most_common(1)
[('c', 7)]
Run Code Online (Sandbox Code Playgroud)

在柜台外,可以根据key功能调整分拣; .sort()并且sorted()都采用callable,允许您指定一个值来对输入序列进行排序; sorted(x, key=x.get, reverse=True)会给你相同的排序x.most_common(),但只返回键,例如:

>>> sorted(x, key=x.get, reverse=True)
['c', 'a', 'b']
Run Code Online (Sandbox Code Playgroud)

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

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

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


Hoo*_*ked 20

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

from collections import Counter, OrderedDict

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

随着输出:

OrderedDict([('c', 7), ('a', 5), ('b', 3)])
{
  "c": 7, 
  "a": 5, 
  "b": 3
}
Run Code Online (Sandbox Code Playgroud)

  • 从 Python 3.7(CPython 为 3.6)开始,不再需要“OrderedDict”,因为“dict”现在保留插入顺序。所以它只是`y = dict(x.most_common())` (8认同)

Inb*_*ose 9

是:

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

使用sorted关键字键和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)]
Run Code Online (Sandbox Code Playgroud)

这适用于所有词典.但是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)]
Run Code Online (Sandbox Code Playgroud)

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

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


Ale*_*eam 8

更一般的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)]
Run Code Online (Sandbox Code Playgroud)

  • `key` 关键字定义排序方式,数字类型前减号表示降序 (2认同)