就像标题说的,我需要编写一个按字母频率对列表进行排序的函数。通常我会提供自己的代码,但我不知道从哪里开始。我确定它很简单,但我不知道该怎么做。我需要他们降序排序,任何帮助表示赞赏,谢谢。按蟒蛇的字母频率排序(降序)
5
A
回答
9
在Python 2.7
或更高版本,你可以使用一个计数器:
>>> mywords = ['red', 'blue', 'red', 'green', 'blue', 'blue']
>>> cnt = Counter(mywords)
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})
按Sorted Word frequency count using python
,如果你需要的字母来代替的话,你可以去这样 http://docs.python.org/dev/library/collections.html#collections.Counter
:>>> 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的或更低,则可以使用等效Counter recipe。
相关问题
- 1. 蟒蛇:排序
- 2. perl - 按数字顺序降序排列,然后按字母顺序排列
- 3. 排序为蟒蛇
- 4. 按字母顺序排序,然后按字母顺序排列
- 5. 按字母顺序排序
- 6. 排序按字母顺序
- 7. 按字母顺序排序
- 8. 按字母顺序排序
- 9. 如何双向排序python列表,按降序排列数字,按升序排列字母排序?
- 10. 排序一个清单:数字升序排列,字母降序
- 11. 排序串入的蟒蛇
- 12. 蟒蛇:排序嵌套的字典
- 13. 排序字典值 - 降我有字母
- 14. 按字母顺序排列PHP排序
- 15. 蟒蛇排序2D字典由指数
- 16. 蟒蛇 - 条件排序
- 17. 蟒蛇 - 泡沫排序
- 18. 蟒蛇排序列表
- 19. 排序蟒蛇嗖导致
- 20. 归并排序蟒蛇3
- 21. 蟒蛇重复排序3
- 22. 按字母顺序排序元素,然后按数字排序
- 23. SORL构面字段按降序排序
- 24. 按降序对数字进行排序
- 25. 蟒蛇,字典创建于频率的字母和值的键出现
- 26. 按字母顺序排序字符串
- 27. MYSQL - 按首字母排序
- 28. 按字母顺序排列
- 29. 按字母排序数组?
- 30. 按字母排序数组?
什么?话? –