繁体   English   中英

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

[英]Sorting a list by frequency of letter in python (decreasing order)

就像标题说的那样,我需要编写一个按字母频率对列表进行排序的函数。 通常我会提供我的代码到目前为止,但我不知道从哪里开始。 我确信这很简单,但我不知道该怎么办。 我需要按降序排序,感谢任何帮助。

在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的Sorted Word频率计数

如果你需要字母而不是单词,你可以这样:

>>> 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)

对于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或更低版本,您可以使用等效的计数器配方

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM