问题背景
统计英文文章中单词的频率,得到之后呢,我不仅想让看到从 a 开头到 z 开头的数据,我还想看到出现频次从高到低的数据,所以有了这篇文章,
初步知识 sorted 函数
sorted(iterable,key,reverse)
,sorted一共有 iterable, key, reverse这三个参数。第一个是要排序的东西要是一个序列,第二个是你用什么准则来排序,是用序列的 原始值呢,还是绝对值呢,亦或者是其他的东西呢,第三个是你是否想让他反序,默认从小到大
字典的 items() 返回的是一个视图对象 python的字典的items(), keys(), values() ,可以简单理解成本一个数据元素是元组的列表
按键排序
freq = {'New': 1, 'to': 1, 'Python': 5, 'or': 2, 'choosing': 1, 'between': 1, '2': 2, 'and': 1, '3?': 1, 'Read': 1, '3.': 1}frq = sorted(freq.items()) ## 按 key 对字典排序dic = dict(frq)print(dic)
{‘2’: 2, ‘3.’: 1, ‘3?’: 1, ‘New’: 1, ‘Python’: 5, ‘Read’: 1, ‘and’: 1, ‘between’: 1, ‘choosing’: 1, ‘or’: 2, ‘to’: 1}
按值排序
freq = {'New': 1, 'to': 1, 'Python': 5, 'or': 2, 'choosing': 1, 'between': 1, '2': 2, 'and': 1, '3?': 1, 'Read': 1, '3.': 1}frq = sorted(freq.items(), key= lambda item : item[1]) ## 按 value 对字典排序dic = dict(frq)print(dic)
{‘New’: 1, ‘to’: 1, ‘choosing’: 1, ‘between’: 1, ‘and’: 1, ‘3?’: 1, ‘Read’: 1, ‘3.’: 1, ‘or’: 2, ‘2’: 2, ‘Python’: 5}