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

标签 python frequency

正如标题所说,我需要编写一个函数来按字母出现的频率对列表进行排序。通常我会提供我目前所拥有的代码,但我不知道从哪里开始。我确定它很简单,但我只是不知道该怎么做。我需要它们按降序排列,感谢任何帮助,谢谢。

最佳答案

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

根据 Sorted Word frequency count using 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)

关于python - 按python中字母的频率对列表进行排序(降序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7961629/

相关文章:

R 计算日期范围之间每月发生的频率

python - ValueWarning : No frequency information was provided, 因此将使用推断频率 MS

python - 使用 try 语句如何避免竞争条件?

python - Pytorch:我们可以直接在 forward() 函数中使用 nn.Module 层吗?

python - 计算一个值的出现次数,直到它更改为另一个值

Python Pandas 数据框 : replace variable by the frequency count

python - Scikit Learn 变量偏差

python - 添加字符串时输出中的额外换行符

python - 接收组播: Does TTL matter?

r - 附加频率表 - 带有缺失值