按字母频率在Python中对列表进行排序(按降序排列)

5

就像标题所说,我需要编写一个函数按字母频率排序列表。通常情况下,我会提供我已经完成的代码,但我不知道该从哪里开始。我相信这是一件简单的事情,但我不知道该做什么。我需要按递减顺序对它们进行排序,任何帮助都将不胜感激,谢谢。

2个回答

9
在Python 2.7或更高版本中,您可以使用一个计数器: http://docs.python.org/dev/library/collections.html#collections.Counter
>>> mywords = ['red', 'blue', 'red', 'green', 'blue', 'blue']
>>> cnt = Counter(mywords)
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})

根据使用Python进行排序的单词频率统计,如果你需要字母而不是单词,可以采用以下方法:
>>> 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或更低版本,您可以使用等效的计数器recipe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接