我们经常在计算机等级考试中遇到词频排序的问题,我们一般先通过生成字典的方法,统计词的频次,然后给字典排序。那么如何快速地给字典按照键值进行排序呢?下面介绍三种方法。第一种方法相对比较常见,但是第二种方法你可能第一次见,第三种方法是比较麻烦的一种,你可以参考一下。

例:有下面的列表dic={'a': 4, 'b': 3, 'c': 2, 'd': 1},如何实现字典的升序排列呢?

第一种:利用自定义函数lambda
>>> dic={'a': 4, 'b': 3, 'c': 2, 'd': 1} >>> sorted(dic.items(), key=lambda x:
x[1]) [('d', 1), ('c', 2), ('b', 3), ('a', 4)]
这里,通过dic.items()获取由字典键名和键值组成的元组列表,然后通过自定义函数,获取元组的第2个元素,作为排序的依据即key,
默认是按照升序排列,如果是降序排列可以把reverse设为True,即:
>>> dic={'a': 4, 'b': 3, 'c': 2, 'd': 1} >>> sorted(dic.items(), key=lambda x:
x[1],reverse=True) {'a': 4, 'b': 3, 'c': 2, 'd': 1}
第二种:利用operator的方法
>>> import operator >>> sorted(xs.items(), key=operator.itemgetter(1)) [('d',
1), ('c', 2), ('b', 3), ('a', 4)]
operator. itemgetter(item)
operator. itemgetter(*items)

功能是返回一个可调用对象,该对象可以使用操作__getitem__()方法从自身的操作中捕获item。如果制定了多个items,返回一个由查询值组成的元组。例如:运行f
=itemgetter(2),然后调用f(r),返回r[2]。这里通过operator获得了dic.items()中的键值。注意operator是内置的包,无需安装。

第三种方法:列表推导式法
>>> dic={'a': 4, 'b': 3, 'c': 2, 'd': 1} >>> tup=[(x[1],x[0]) for x in
dic.items()]#元素互换位置 >>> sorted(tup) #排序 [(1, 'd'), (2, 'c'), (3, 'b'), (4,
'a')] >>> [(x[1],x[0]) for x in dic.items()] >>> [(x[1],x[0]) for x in tup]
#换回原来的位置 >>> [('d', 1), ('c', 2), ('b', 3), ('a', 4)]
用列表推导式,交换元组中元素的位置,排序后再交换回来,这种方法有点儿麻烦,但是逻辑清楚,适合新手。还有哪些好的方法,欢迎大家提出来,一起来交流。

第四种方法:用Counter的方法
from collections import Counter dic={'a': 4, 'b': 3, 'c': 2, 'd': 1} count =
Counter(dic) print(list(count.items()))
总结:以上四种方法就是常见的排序方法,供大家参考学习。

技术
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信