python对列表和字典进行排序的方法

我们之前已经学过对列表进行排序了,比较简单,主要使用的sort和sorted两个方法,这两个方法可以看看我的历史笔记:https://sulao.cn/post/370.html

1.列表的排序之前的笔记即可

2.包含字典的列表进行排序

对包含字典的列表进行排序的方法,我们需要使用到operator模块

#!/usr/bin/python3
#coding: utf-8
import operator
ls = [{"id": 1, "name": "test1", "status": 1},{"id": 3, "name": "test2", "status": 2},{"id": 2, "name": "test3", "status": 1}]
ls_sort = sorted(ls, key=operator.itemgetter('status'), reverse=True)
print(ls_sort)

打印

{BAB68847-D752-45CA-A2AF-D54526F40B1B}_20190604112223.jpg

以上示例我们是根据status来进行排倒序,如果需要正序,只需要将reverse参数的值改为Flase即可

3.对字典进行排序

#!/usr/bin/python3
#coding: utf-8
ls_dict = {'1':1, '3':3, '2':5, '4':4}
ls_dict_zip = zip(ls_dict.values(), ls_dict.keys())
ls_dict_tuple = sorted(ls_dict_zip, reverse=True)
for p in ls_dict_tuple:
print(p)

打印结果为

(5, '2')
(4, '4')
(3, '3')
(1, '1')

都转换为元祖了

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://sulao.cn/post/682.html

我要评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。