2015-11-04 40 views
3

如何根據櫃檯對Counter.mostCommon的結果進行排序,然後將值?如何按照字典順序(通過計數器,然後按值)對Counter.mostCommon(n)的結果進行排序?

我原來的代碼:

from collections import Counter 
for counter in Counter("abcdefg").most_common(3): 
    print(counter[0], counter[1]) 

的輸出是不同的每一次,由於每個值具有爲1 計數有時它是

有時

b 1 
d 1 
f 1 

等等。

我想這樣:

a 1 
b 1 
c 1 

我也試着整理得到的元組::

from collections import Counter 
for counter in sorted(Counter("abcdefg").most_common(3), key=lambda x: x[0]): print(counter[0], counter[1]) 

和排序字符串

from collections import Counter 
for counter in Counter(sorted("abcdefg")).most_common(3): print(counter[0], counter[1]) 

,但我得到了同樣的不可預測結果

回答

3

The p這裏的謎題是Counter字典是無序的,而most_common並不關心密鑰。要做到這一點,你需要排序詞典的項目,然後拉出3個最常見的。

counter = Counter('abcdef') 
most_common = sorted(counter.items(), key=lambda pair: (-pair[1], pair[0])) 

這將首先排序-pair[1](計數)。由於負面因素,較高的數字會首先出現。接下來我們對pair[0](關鍵字)進行排序,它將以正常遞增順序按字典順序排列。

從這裏,你需要切下你想要的物品......

most_common[:3] 

或者,我們可以採取一個頁面出來的the source code和重新實現most_common取鑰匙進入帳戶。

import heapq as _heapq 

def most_common(counter, n=None): 
    '''List the n most common elements and their counts from the most 
    common to the least. If n is None, then list all element counts. 

    >>> Counter('abcdeabcdabcaba').most_common(3) 
    [('a', 5), ('b', 4), ('c', 3)] 

    ''' 
    # Emulate Bag.sortedByCount from Smalltalk 
    sort_key = lambda pair: (-pair[1], pair[0]) 
    if n is None: 
     return sorted(counter.iteritems(), key=sort_key) 
    return _heapq.nsmallest(n, counter.iteritems(), key=sort_key) 
+0

我在每次執行時得到不同的有序結果。 –

+0

@JamesWierzba - 對,對不起。更新我的解決方案 – mgilson

+0

這工作,謝謝。我修改了'iteritems'到'items'的答案,因爲我在python 3.4.3上。謝謝你的幫助。 –

相關問題