Python sorted对list和dict排序


Posted in Python onJune 09, 2020

sorted语法

sorted(iterable, key=None, reverse=False)

参数说明:

 - iterable -- 可迭代对象。
 - key --主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
 - reverse -- 排序规则,reverse = True 降序 , reverse = False 升序(默认)。

返回:
 - 一个新list对象 

sorted对字典dict排序

①按键key排序

from operator import itemgetter
dict = {3: 'B', 1: 'A', 2: 'C'}

# 按key升序  .items()取得3个(key,value)
# lambda x: x[0]取(key,value)的key  即(3,1,2)
d1 = sorted(dict.items(), key=lambda x: x[0], reverse=False) # <class 'list'>

# 按key降序  itemgetter类似lambda
d2 = sorted(dict.items(), key=itemgetter(0), reverse=True) # <class 'list'>

# 输出
print(d1, type(d1)) # [(1, 'A'), (2, 'C'), (3, 'B')] <class 'list'>
print(d2, type(d2)) # [(3, 'B'), (2, 'C'), (1, 'A')] <class 'list'>

[(1, ‘A'), (2, ‘C'), (3, ‘B')] <class ‘list'>
[(3, ‘B'), (2, ‘C'), (1, ‘A')] <class ‘list'>

②按值value排序

from operator import itemgetter
dict = {3: 'B', 1: 'A', 2: 'C'}

# 按value升序  .items()取得3个(key,value)
# lambda x: x[1]取(key,value)的value  即('B','A','C')
d3 = sorted(dict.items(), key=lambda x: x[1], reverse=False) # <class 'list'>

# 按value降序  itemgetter类似lambda
d4 = sorted(dict.items(), key=itemgetter(1), reverse=True) # <class 'list'>

print(d3, type(d3)) # [(1, 'A'), (3, 'B'), (2, 'C')] <class 'list'>
print(d4, type(d4)) # [(2, 'C'), (3, 'B'), (1, 'A')] <class 'list'>

[(1, ‘A'), (3, ‘B'), (2, ‘C')] <class ‘list'>
[(2, ‘C'), (3, ‘B'), (1, ‘A')] <class ‘list'>

sorted排序list

①按一种规则排序list

from operator import itemgetter
data = [('c', 3, 'Apple'), ('d', 1, 'Cat'), ('a', 2, 'Banana')]
# 根据字母升序
print(sorted(data, key=lambda x: x[0], reverse=False)) # <class 'list'>
# 根据数字升序
print(sorted(data, key=lambda x: x[1], reverse=False)) # <class 'list'>
# 根据单词升序
print(sorted(data, key=lambda x: x[2], reverse=False)) # <class 'list'>

[('a', 2, 'Banana'), ('c', 3, 'Apple'), ('d', 1, 'Cat')]
[('d', 1, 'Cat'), ('a', 2, 'Banana'), ('c', 3, 'Apple')]
[('c', 3, 'Apple'), ('a', 2, 'Banana'), ('d', 1, 'Cat')]

②按多种规则排序list

# 先按照成绩降序排序,相同成绩的按照名字升序排序:
d1 = [{'name':'alice', 'score':38}, {'name':'bob', 'score':18}, {'name':'darl', 'score':28}, {'name':'christ', 'score':28}]
l = sorted(d1, key=lambda x:(-x['score'], x['name']))
print(l)

[{'name': 'alice', 'score': 38}, {'name': 'christ', 'score': 28}, {'name': 'darl', 'score': 28}, {'name': 'bob', 'score': 18}]

sorted排序list和dict的混合

 先看看我们排序的有哪些类型的数据结构

#### 二维list排序
l1 = [['Bob', 95.00, 'A'], ['Alan', 86.0, 'C'], ['Mandy', 82.5, 'A'], ['Rob', 86, 'E']]

#### list中混合字典
l2 = [{'name':'alice', 'score':38}, {'name':'bob', 'score':18}, {'name':'darl', 'score':28}, {'name':'christ', 'score':28}]

#### 字典中混合list
d1 = {'Li': ['M', 7], 'Zhang': ['E', 2], 'Wang': ['P', 3], 'Du': ['C', 2], 'Ma': ['C', 9], 'Zhe': ['H', 7]}

#### 对字典中的多维list进行排序
d2 = {
  'Apple': [['44', 88], ['11', 33], ['22', 88]],
  'Banana': [['55', 43], ['11', 68], ['44', 22]],
  'Orange':[['22', 22], ['55', 41], ['44', 42], ['33', 22]]
}

二维list排序

from operator import itemgetter
l1 = [['Bob', 95.00, 'A'], ['Alan', 86.0, 'C'], ['Mandy', 82.5, 'A'], ['Rob', 86, 'E']]
# 按先按成绩号升序,再按成绩数值升序
print(sorted(l1, key=itemgetter(2, 1), reverse=False))
# 按先按成绩号升序,再按成绩数值降序序
print(sorted(l1, key=lambda x:(x[2], -x[1]), reverse=False))

[[‘Mandy', 82.5, ‘A'], [‘Bob', 95.0, ‘A'], [‘Alan', 86.0, ‘C'], [‘Rob', 86, ‘E']]
[[‘Bob', 95.0, ‘A'], [‘Mandy', 82.5, ‘A'], [‘Alan', 86.0, ‘C'], [‘Rob', 86, ‘E']]

2. list中混合字典

from operator import itemgetter
# 先按照成绩降序排序,相同成绩的按照名字升序排序:
l2 = [{'name':'alice', 'score':38}, {'name':'bob', 'score':18}, {'name':'darl', 'score':28}, {'name':'christ', 'score':28}]
print(sorted(l2, key=lambda x:(-x['score'], x['name'])))
print(sorted(l2, key=itemgetter('score', 'name')))

[{‘name': ‘alice', ‘score': 38}, {‘name': ‘christ', ‘score': 28}, {‘name': ‘darl', ‘score': 28}, {‘name': ‘bob', ‘score': 18}]
[{‘name': ‘bob', ‘score': 18}, {‘name': ‘christ', ‘score': 28}, {‘name': ‘darl', ‘score': 28}, {‘name': ‘alice', ‘score': 38}]

3. 字典中混合list

d1 = {'Li': ['M', 7], 'Zhang': ['E', 2], 'Wang': ['P', 3], 'Du': ['C', 2], 'Ma': ['C', 9], 'Zhe': ['H', 7]}
# sort返回的是list,如果需要转为dict,再sorted前面套一个dict()就可以了
print(sorted(d1.items(), key=lambda x:(x[1][1], -ord(x[1][0]) ))) # 对字符比较需要ord。如果是'123'字符串数字可以使用int。
# print(sorted(d1.items(), key=lambda x:(x[1][1], -ord(x[1][0]) )))

[(‘Zhang', [‘E', 2]), (‘Du', [‘C', 2]), (‘Wang', [‘P', 3]), (‘Li', [‘M', 7]), (‘Zhe', [‘H', 7]), (‘Ma', [‘C', 9])]

4. 对字典中的多维list进行排序

d2 = {
  'Apple': [['44', 88], ['11', 33], ['22', 88]],
  'Banana': [['55', 43], ['11', 68], ['44', 22]],
  'Orange':[['22', 22], ['55', 41], ['44', 42], ['33', 22]]
}
for key, value in d2.items():
  d2[key] = sorted(value, key=lambda x:(x[1], -int(x[0]))) # 按list第二列升序,相同则按第一列降序,参考二维list排序
print(d2)

{‘Apple': [[‘11', 33], [‘44', 88], [‘22', 88]], ‘Banana': [[‘44', 22], [‘55', 43], [‘11', 68]], ‘Orange': [[‘33', 22], [‘22', 22], [‘52', 41], [‘44', 42]]}

到此这篇关于Python sorted对list和dict排序的文章就介绍到这了,更多相关Python sorted对list和dict排序内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python实例分享:快速查找出被挂马的文件
Jun 08 Python
python中类的一些方法分析
Sep 25 Python
详解Python发送邮件实例
Jan 10 Python
python使用str &amp; repr转换字符串
Oct 13 Python
浅谈Python实现Apriori算法介绍
Dec 20 Python
matplotlib subplots 设置总图的标题方法
May 25 Python
基于python历史天气采集的分析
Feb 14 Python
Python3+Selenium+Chrome实现自动填写WPS表单
Feb 12 Python
Python 防止死锁的方法
Jul 29 Python
python爬取音频下载的示例代码
Oct 19 Python
python实现银行账户系统
Feb 22 Python
解析目标检测之IoU
Jun 26 Python
python初步实现word2vec操作
Jun 09 #Python
Python生成随机验证码代码实例解析
Jun 09 #Python
在python下实现word2vec词向量训练与加载实例
Jun 09 #Python
Python实现寻找回文数字过程解析
Jun 09 #Python
pycharm 关掉syntax检查操作
Jun 09 #Python
Python控制台实现交互式环境执行
Jun 09 #Python
使用pycharm和pylint检查python代码规范操作
Jun 09 #Python
You might like
我的论坛源代码(七)
2006/10/09 PHP
Apache2 httpd.conf 中文版
2006/11/17 PHP
在命令行下运行PHP脚本[带参数]的方法
2010/01/22 PHP
php统计文件大小,以GB、MB、KB、B输出
2011/05/29 PHP
php中获取主机名、协议及IP地址的方法
2014/11/18 PHP
php 时间time与日期date之间的使用详解及区别
2016/11/07 PHP
PHP 文件锁与进程锁的使用示例
2017/08/07 PHP
[原创]PHP获取数组表示的路径方法分析【数组转字符串】
2017/09/01 PHP
php使用curl_init()和curl_multi_init()多线程的速度比较详解
2018/08/15 PHP
JavaScript 对象的属性和方法4种不同的类型
2010/03/19 Javascript
jQuery数据缓存功能的实现思路及简单模拟
2013/05/27 Javascript
jquery easyui滚动条部分设置介绍
2013/09/12 Javascript
nodejs中实现sleep功能实例
2015/03/24 NodeJs
Webpack 实现 Node.js 代码热替换
2015/10/22 Javascript
JavaScript实现经典排序算法之冒泡排序
2016/12/28 Javascript
js 函数式编程学习笔记
2017/03/25 Javascript
使用 NodeJS+Express 开发服务端的简单介绍
2017/04/07 NodeJs
解决vue页面刷新或者后退参数丢失的问题
2018/03/13 Javascript
浅析java线程中断的办法
2018/07/29 Javascript
使用Python脚本对Linux服务器进行监控的教程
2015/04/02 Python
设计模式中的原型模式在Python程序中的应用示例
2016/03/02 Python
python制作爬虫爬取京东商品评论教程
2016/12/16 Python
python实发邮件实例详解
2019/11/11 Python
python中property和setter装饰器用法
2019/12/19 Python
Python如何实现后端自定义认证并实现多条件登陆
2020/06/22 Python
Python实现封装打包自己写的代码,被python import
2020/07/12 Python
Django如何在不停机的情况下创建索引
2020/08/02 Python
Python使用for生成列表实现过程解析
2020/09/22 Python
浅谈html5之sse服务器发送事件EventSource介绍
2017/08/28 HTML / CSS
Java里面StringBuilder和StringBuffer有什么区别
2016/06/06 面试题
中科创达面试题
2016/12/28 面试题
优质的学校老师推荐信
2013/10/28 职场文书
大学军训通讯稿
2014/01/13 职场文书
2014年园林绿化工作总结
2014/12/11 职场文书
2014企业年终工作总结
2014/12/23 职场文书
CentOS7安装MySQL8的超级详细教程(无坑!)
2022/06/10 Servers