2017-07-12 148 views
-1

值爲了我有我想通過以下方式進行排序計數器:如何排序計數器按字母順序然後在Python

Counter({'M': 9, 'L': 5, 'P': 5, 'S': 2, 'd': 1, 'T': 1}) 

,當我用我的代碼,這裏是它給了我:

Counter({'M': 9, 'P': 5, 'L': 5, 'S': 2, 'T': 1, 'd': 1}) 

我想排序的函數(),但是當我使用它,它的返回值是不是反了。

這是我的代碼,你會怎麼做?

def most_encountered_letters(dictionnary): 
    counter = collections.Counter() 
    for line in dictionnary: 
     words = line.split(',')[0].split(' ') 
     for word in words: 
      counter[word[0]] += 1 

    print(counter)                           
    return counter.most_common(5) 
+1

'Counter'是一個'Dict'子類,所以根據定義它是未排序的,如果你嘗試使用'sorted()'它必須返回一個非'Dict'類。您可以將結果移動到['OrderedDict'](https://stackoverflow.com/a/9001529/1270789)。我想,但我的問題是「你爲什麼要排序?」,因爲你的實際問題可能更好地解決。最後,這裏有很多方法來排序(https://wiki.python.org/moin/HowTo/Sorting)。順便說一句,Python 2.x或3.x? –

+0

這是沒有辦法在Python中排序'Dict',唯一的方法是查看鏈接https://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value?page=1&tab=投票#tab-top – Wen

+0

_確切!你的非答案徹底改變了你的問題,並使兩個答案無效。 –

回答

2

Counter s是無序的。他們是dict的子類,並且像dict一樣,未訂購。說「排序的Counter」沒有意義。您可以獲得項目的列表中Counter整理你想要的方式,例如:如果你想要一個有序Mapping

>>> from collections import Counter 
>>> c = Counter({'M': 9, 'L': 5, 'P': 5, 'S': 2, 'd': 1, 'T': 1}) 
>>> c 
Counter({'M': 9, 'L': 5, 'P': 5, 'S': 2, 'T': 1, 'd': 1}) 
>>> sorted(c.items(), key= lambda t: (t[1], t[0]), reverse=True) 
[('M', 9), ('P', 5), ('L', 5), ('S', 2), ('d', 1), ('T', 1)] 

,你要麼必須使用內置OrderedDict,或實現自己的。我們可以使用多重繼承來重新使用內置類來獲得我們想要的內容。這是一個配方straight from the docs

class OrderedCounter(Counter, OrderedDict): 
    'Counter that remembers the order elements are first encountered' 

    def __repr__(self): 
     return '%s(%r)' % (self.__class__.__name__, OrderedDict(self)) 

    def __reduce__(self): 
     return self.__class__, (OrderedDict(self),) 

因此,在行動:

>>> oc = OrderedCounter() 
>>> for k,v in sorted(c.items(), key= lambda t: (t[1], t[0]), reverse=True): 
...  oc[k] = v 
... 
>>> oc 
OrderedCounter(OrderedDict([('M', 9), ('P', 5), ('L', 5), ('S', 2), ('d', 1), ('T', 1)])) 
>>> for k,v in oc.items(): 
... print(k,v) 
... 
M 9 
P 5 
L 5 
S 2 
d 1 
T 1 
>>> 

更重要的是,你應該考慮爲什麼你需要一個有序Counter ...你真的需要一個?

相關問題