在Python中按字母出现频率降序排序列表
就像标题说的,我需要写一个函数,按照字母出现的频率来排序一个列表。通常我会把我写的代码发出来,但我现在完全不知道从哪里开始。我相信这应该是个简单的事情,但我就是不知道该怎么做。我需要把它们按出现频率从高到低排序,任何帮助都很感谢,谢谢。
2 个回答
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配方。
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)