-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)
'Counter'是一個'Dict'子類,所以根據定義它是未排序的,如果你嘗試使用'sorted()'它必須返回一個非'Dict'類。您可以將結果移動到['OrderedDict'](https://stackoverflow.com/a/9001529/1270789)。我想,但我的問題是「你爲什麼要排序?」,因爲你的實際問題可能更好地解決。最後,這裏有很多方法來排序(https://wiki.python.org/moin/HowTo/Sorting)。順便說一句,Python 2.x或3.x? –
這是沒有辦法在Python中排序'Dict',唯一的方法是查看鏈接https://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value?page=1&tab=投票#tab-top – Wen
_確切!你的非答案徹底改變了你的問題,並使兩個答案無效。 –