除了做反向列表推导式的列表推导式之外,是否有python方式按值对计数器排序?如果是这样,它比这个快:

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

当前回答

对@MartijnPieters的答案的一个相当不错的补充是,从集合中获得一个按事件排序的字典。Most_common只返回一个元组。我经常将其与json输出相结合,以获得方便的日志文件:

from collections import Counter, OrderedDict

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

输出:

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

其他回答

Yes:

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

使用排序关键字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)]

这适用于所有字典。然而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)]

你也可以指定你想看多少项:

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

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

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

它会以最有效的方式做到这一点;如果你要求一个Top N而不是所有的值,使用一个heapq来代替直接排序:

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

在计数器之外,排序总是可以根据一个关键功能进行调整;.sort()和sorted()都接受callable,让你指定一个值对输入序列进行排序;排序(x = x的关键。get, reverse=True)会给你与x.most_common()相同的排序,但只返回键,例如:

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

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

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

有关更多信息,请参阅Python排序howto。

对@MartijnPieters的答案的一个相当不错的补充是,从集合中获得一个按事件排序的字典。Most_common只返回一个元组。我经常将其与json输出相结合,以获得方便的日志文件:

from collections import Counter, OrderedDict

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

输出:

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

更通用的排序,其中key关键字定义了排序方法,数值类型前的减号表示降序:

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