Python sorted函数详解(高级篇)


Posted in Python onSeptember 18, 2018

sorted 用于对集合进行排序(这里集合是对可迭代对象的一个统称,他们可以是列表、字典、set、甚至是字符串),它的功能非常强大

1、对列表排序,返回的对象不会改变原列表

list = [1,5,7,2,4]

sorted(list)
Out[87]: [1, 2, 4, 5, 7]
#可以设定时候排序方式,默认从小到大,设定reverse = False 可以从大到小
sorted(list,reverse=False)
Out[88]: [1, 2, 4, 5, 7]

sorted(list,reverse=True)
Out[89]: [7, 5, 4, 2, 1]

2、根据自定义规则来排序,使用参数:key

# 使用key,默认搭配lambda函数使用
sorted(chars,key=lambda x:len(x))
Out[92]: ['a', 'is', 'boy', 'bruce', 'handsome']

sorted(chars,key=lambda x:len(x),reverse= True)
Out[93]: ['handsome', 'bruce', 'boy', 'is', 'a']

3、根据自定义规则来排序,对元组构成的列表进行排序

tuple_list = [('A', 1,5), ('B', 3,2), ('C', 2,6)]
#key=lambda x: x[1]中可以任意选定x中可选的位置进行排序
sorted(tuple_list, key=lambda x: x[1]) 

Out[94]: [('A', 1, 5), ('C', 2, 6), ('B', 3, 2)]

sorted(tuple_list, key=lambda x: x[0])
Out[95]: [('A', 1, 5), ('B', 3, 2), ('C', 2, 6)]

sorted(tuple_list, key=lambda x: x[2])
Out[96]: [('B', 3, 2), ('A', 1, 5), ('C', 2, 6)]

4、排序的元素是自定义类

class tuple_list:
 def __init__(self, one, two, three):
  self.one = one
  self.two = two
  self.three = three
 def __repr__(self):
  return repr((self.one, self.two, self.three))


tuple_list_ = [tuple_list('A', 1,5), tuple_list('B', 3,2), tuple_list('C', 2,6)]

sorted(tuple_list_, key=lambda x: x.one)
Out[104]: [('A', 1, 5), ('B', 3, 2), ('C', 2, 6)]

sorted(tuple_list_, key=lambda x: x.two)
Out[105]: [('A', 1, 5), ('C', 2, 6), ('B', 3, 2)]

sorted(tuple_list_, key=lambda x: x.three)
Out[106]: [('B', 3, 2), ('A', 1, 5), ('C', 2, 6)]

5、sorted 也可以根据多个字段来排序

class tuple_list:
 def __init__(self, one, two, three):
  self.one = one
  self.two = two
  self.three = three
 def __repr__(self):
  return repr((self.one, self.two, self.three))

tuple_list_ = [tuple_list('C', 1,5), tuple_list('A', 3,2), tuple_list('C', 2,6)]
# 首先根据one的位置来排序,然后根据two的位置来排序
sorted(tuple_list_, key=lambda x:(x.one, x.two))
Out[112]: [('A', 3, 2), ('C', 1, 5), ('C', 2, 6)]

6、使用operator 中的itemgetter方法和attrgetter方法

tuple_list = [('A', 1,5), ('B', 3,2), ('C', 2,6)]

class tuple_list_class:
 def __init__(self, one, two, three):
  self.one = one
  self.two = two
  self.three = three
 def __repr__(self):
  return repr((self.one, self.two, self.three))

tuple_list_ = [tuple_list_class('C', 1,5), tuple_list_class('A', 3,2), tuple_list_class('C', 2,6)]

from operator import itemgetter
sorted(tuple_list, key=itemgetter(1))

Out[119]: [('A', 1, 5), ('C', 2, 6), ('B', 3, 2)]

from operator import attrgetter
sorted(tuple_list_, key=attrgetter('one')) # attrgetter 传入的参数必须是str

Out[120]: [('A', 3, 2), ('C', 1, 5), ('C', 2, 6)]

# 如果是根据多个类的参数排序,按照参数定义顺序
from operator import attrgetter
sorted(tuple_list_, key=attrgetter('two','one'))

Out[121]: [('C', 1, 5), ('C', 2, 6), ('A', 3, 2)]

高级用法

有时候,我们要处理的数据内的元素不是一维的,而是二维的甚至是多维的,那要怎么进行排序呢?这时候,sorted()函数内的key参数就派上用场了!从帮助信息上可以了解到,key参数可传入一个自定义函数。那么,该如何使用呢?让我们看看如下代码:

>>>l=[('a', 1), ('b', 2), ('c', 6), ('d', 4), ('e', 3)]
>>>sorted(l, key=lambda x:x[0])
Out[39]: [('a', 1), ('b', 2), ('c', 6), ('d', 4), ('e', 3)]
>>>sorted(l, key=lambda x:x[0], reverse=True)
Out[40]: [('e', 3), ('d', 4), ('c', 6), ('b', 2), ('a', 1)]
>>>sorted(l, key=lambda x:x[1])
Out[41]: [('a', 1), ('b', 2), ('e', 3), ('d', 4), ('c', 6)]
>>>sorted(l, key=lambda x:x[1], reverse=True)
Out[42]: [('c', 6), ('d', 4), ('e', 3), ('b', 2), ('a', 1)]

这里,列表里面的每一个元素都为二维元组,key参数传入了一个lambda函数表达式,其x就代表列表里的每一个元素,然后分别利用索引返回元素内的第一个和第二个元素,这就代表了sorted()函数利用哪一个元素进行排列。而reverse参数就如同上面讲的一样,起到逆排的作用。默认情况下,reverse参数为False。
当然,正如一开始讲到的那样,如果想要对列表直接进行排序操作,可以用成员方法sort()来做:

>>>l.sort(key=lambda x : x[1])
>>>l
Out[45]: [('a', 1), ('b', 2), ('e', 3), ('d', 4), ('c', 6)]
>>>l.sort(key=lambda x : x[1], reverse=True)
>>>l
Out[47]: [('c', 6), ('d', 4), ('e', 3), ('b', 2), ('a', 1)]

对于三维及以上的数据排排序,上述方法同样适用。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对三水点靠木的支持。如果你想了解更多相关内容请查看下面相关链接

Python 相关文章推荐
浅谈Python对内存的使用(深浅拷贝)
Jan 17 Python
python logging重复记录日志问题的解决方法
Jul 12 Python
python实现彩票系统
Jun 28 Python
Django跨域请求CSRF的方法示例
Nov 11 Python
flask session组件的使用示例
Dec 25 Python
浅谈python之高阶函数和匿名函数
Mar 21 Python
Python匿名函数及应用示例
Apr 09 Python
python实现点击按钮修改数据的方法
Jul 17 Python
Python从列表推导到zip()函数的5种技巧总结
Oct 23 Python
Python drop方法删除列之inplace参数实例
Jun 27 Python
ITK 实现多张图像转成单个nii.gz或mha文件案例
Jul 01 Python
PyTorch预训练Bert模型的示例
Nov 17 Python
python 2.7.13 安装配置方法图文教程
Sep 18 #Python
Python DataFrame.groupby()聚合函数,分组级运算
Sep 18 #Python
python 3.6.2 安装配置方法图文教程
Sep 18 #Python
Python对CSV、Excel、txt、dat文件的处理
Sep 18 #Python
python 3.6.4 安装配置方法图文教程
Sep 18 #Python
python 3.6.5 安装配置方法图文教程
Sep 18 #Python
python的pip安装以及使用教程
Sep 18 #Python
You might like
150kHz到30Mhz完全冲浪手册
2020/03/20 无线电
站长助手-网站web在线管理程序 v1.0 下载
2007/05/12 PHP
PHP无刷新上传文件实现代码
2011/09/19 PHP
php生成二维码时出现中文乱码的解决方法
2014/12/18 PHP
PHP中COOKIES使用示例
2015/07/26 PHP
thinkPHP5.0框架整体架构总览【应用,模块,MVC,驱动,行为,命名空间等】
2017/03/25 PHP
jQuery.extend 函数详解
2012/02/03 Javascript
Javascript级联下拉菜单以及AJAX数据验证核心代码
2013/05/10 Javascript
用原生JS获取CLASS对象(很简单实用)
2014/10/15 Javascript
7个去伪存真的JavaScript面试题
2016/01/07 Javascript
Javascript中的迭代、归并方法详解
2016/06/14 Javascript
JavaScript暂停和继续定时器的实现方法
2016/07/18 Javascript
jQuery leonaScroll 1.1 自定义滚动条插件(推荐)
2016/09/17 Javascript
基于jQuery实现文字打印动态效果
2017/04/21 jQuery
基于jQuery封装的分页组件
2017/06/26 jQuery
two.js之实现动画效果示例
2017/11/06 Javascript
jquery判断滚动条距离顶部的距离方法
2018/09/05 jQuery
使用 UniApp 实现小程序的微信登录功能
2020/06/09 Javascript
[00:27]DOTA2战队VP、Secret贺新春
2018/02/11 DOTA
Python FTP操作类代码分享
2014/05/13 Python
python在Windows下安装setuptools(easy_install工具)步骤详解
2016/07/01 Python
利用Python自动监控网站并发送邮件告警的方法
2016/08/24 Python
Python函数式编程
2017/07/20 Python
如何理解python对象
2020/06/21 Python
Html5实现iPhone开机界面示例代码
2013/06/30 HTML / CSS
HTML5+lufylegend实现游戏中的卷轴
2016/02/29 HTML / CSS
Maisons du Monde德国:法国家具和装饰的市场领导者
2019/07/26 全球购物
世界上最受欢迎的花店:1-800-Flowers.com
2020/06/01 全球购物
环境科学专业个人求职信
2013/09/26 职场文书
2014年仓库保管员工作总结
2014/12/03 职场文书
三好学生事迹材料
2014/12/24 职场文书
会计简历自我评价
2015/03/10 职场文书
严以律己专题学习研讨会发言材料
2015/11/09 职场文书
为什么mysql字段要使用NOT NULL
2021/05/13 MySQL
使用Python的开发框架Brownie部署以太坊智能合约
2021/05/28 Python
python字符串拼接.join()和拆分.split()详解
2021/11/23 Python