2014-01-06 37 views
48

除了做列表理解逆序列表理解,有没有pythonic的方式来按值排序计数器?如果是这样,这是比这更快:如何按价值对计数器进行排序? - 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) 

回答

101

使用Counter.most_common() method,它会项目排序:

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

它会以最有效的方式这样做;如果你问一个前N个,而不是所有的价值观,一个heapq代替直排序:

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

外面柜台,排序总是可以根据key功能进行调整; .sort()sorted()都采用可调用的方式,可以指定一个值来对输入序列进行排序; sorted(x, key=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 sorting howto信息。

4

是:

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

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

另一种方式来排序逆转是关键功能设置为'LAMDA我:-i [1 ]' –

5

一个相当不错的除了@MartijnPieters答案是拿回字典由发生排序,因为只有Collections.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 
}