2011-11-01 69 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