2014-01-06 39 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 
} 
相關問題