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