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数组的处理代码
Jan 04 Python
用python登录Dr.com思路以及代码分享
Jun 25 Python
Python使用smtplib模块发送电子邮件的流程详解
Jun 27 Python
pygame 精灵的行走及二段跳的实现方法(必看篇)
Jul 10 Python
Python3实现的字典、列表和json对象互转功能示例
May 22 Python
对python中矩阵相加函数sum()的使用详解
Jan 28 Python
pytorch实现线性拟合方式
Jan 15 Python
完美解决TensorFlow和Keras大数据量内存溢出的问题
Jul 03 Python
使用Python-OpenCV消除图像中孤立的小区域操作
Jul 05 Python
Python+Matplotlib图像上指定坐标的位置添加文本标签与注释
Apr 11 Python
宝塔更新Python及Flask项目的部署
Apr 11 Python
Python创建SQL数据库流程逐步讲解
Sep 23 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
Youku 视频绝对地址获取的方法详解
2013/06/26 PHP
php生成N个不重复的随机数实例
2013/11/12 PHP
浅析php中json_encode()和json_decode()
2014/05/25 PHP
php析构函数的简单使用说明
2015/08/24 PHP
JQuery 无废话系列教程(一) jquery入门 [推荐]
2009/06/23 Javascript
JQuery获取各种宽度、高度(format函数)实例
2013/03/04 Javascript
js自动生成的元素与页面原有元素发生堆叠的解决方法
2013/10/24 Javascript
jQuery select表单提交省市区城市三级联动核心代码
2014/06/09 Javascript
js实现仿QQ秀换装效果的方法
2015/03/04 Javascript
JS查找字符串中出现次数最多的字符
2016/09/05 Javascript
纯JS打造网页中checkbox和radio的美化效果
2016/10/13 Javascript
jquery.cookie.js的介绍与使用方法
2017/02/09 Javascript
在Mac下彻底卸载node和npm的方法
2018/05/16 Javascript
vue操作下拉选择器获取选择的数据的id方法
2018/08/24 Javascript
python使用cookielib库示例分享
2014/03/03 Python
python遍历 truple list dictionary的几种方法总结
2016/09/11 Python
python  创建一个保留重复值的列表的补码
2018/10/15 Python
Python中bisect的使用方法
2019/12/31 Python
Python unittest 自动识别并执行测试用例方式
2020/03/09 Python
关于Python turtle库使用时坐标的确定方法
2020/03/19 Python
解决python中import文件夹下面py文件报错问题
2020/06/01 Python
详解python with 上下文管理器
2020/09/02 Python
python音频处理的示例详解
2020/12/23 Python
HTML5之SVG 2D入门13—svg对决canvas及长处和适用场景分析
2013/01/30 HTML / CSS
匡威帆布鞋美国官网:Converse美国
2016/08/22 全球购物
英国户外玩具儿童游乐设备网站:TP Toys(蹦床、攀爬框架、秋千、滑梯和游戏屋)
2018/04/09 全球购物
澳大利亚在线批发商:Simply Wholesale
2021/02/24 全球购物
计算机应用专业毕业生求职信
2013/10/24 职场文书
学习党的群众路线教育实践活动心得体会
2014/03/01 职场文书
小学综合实践活动总结
2014/07/07 职场文书
管理工程专业求职信
2014/08/10 职场文书
优秀班组申报材料
2014/12/25 职场文书
2015秋季新学期开学寄语
2015/05/28 职场文书
2016学习依法治国心得体会
2016/01/15 职场文书
大学生党员暑假实践(活动总结)
2019/08/21 职场文书
浅谈MySQL next-key lock 加锁范围
2021/06/07 MySQL