2011-11-01 31 views
5

就像標題說的,我需要編寫一個按字母頻率對列表進行排序的函數。通常我會提供自己的代碼,但我不知道從哪裏開始。我確定它很簡單,但我不知道該怎麼做。我需要他們降序排序,任何幫助表示讚賞,謝謝。按蟒蛇的字母頻率排序(降序)

+1

什麼?話? –

回答

9
在Python 2.7

或更高版本,你可以使用一個計數器:

>>> mywords = ['red', 'blue', 'red', 'green', 'blue', 'blue'] 
>>> cnt = Counter(mywords) 
>>> cnt 
Counter({'blue': 3, 'red': 2, 'green': 1}) 

Sorted Word frequency count using python

,如果你需要的字母來代替的話,你可以去這樣 http://docs.python.org/dev/library/collections.html#collections.Counter

>>> mywords = ['red', 'blue', 'red', 'green', 'blue', 'blue'] 
>>> myletters=list("".join(mywords)) 
>>> myletters 
['r', 'e', 'd', 'b', 'l', 'u', 'e', 'r', 'e', 'd', 'g', 'r', 'e', 'e', 'n', 'b', 'l', 'u', 'e', 'b', 'l', 'u', 'e'] 
>>> Counter(myletters) 
4

對於Python2.7 +,使用collections.Counter及其most_common方法:

import collections 

text='abccccabcbb' 
count=collections.Counter(text) 

print(count.most_common()) 
# [('c', 5), ('b', 4), ('a', 2)] 

print(''.join(letter*freq for letter,freq in count.most_common())) 
# cccccbbbbaa 

對於python2.6的或更低,則可以使用等效Counter recipe