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爬虫之神器正则表达式
Nov 06 Python
在Mac OS上使用mod_wsgi连接Python与Apache服务器
Dec 24 Python
详解python进行mp3格式判断
Dec 23 Python
Python基础语言学习笔记总结(精华)
Nov 14 Python
Django基于ORM操作数据库的方法详解
Mar 27 Python
Python叠加两幅栅格图像的实现方法
Jul 05 Python
Python3中configparser模块读写ini文件并解析配置的用法详解
Feb 18 Python
python numpy生成等差数列、等比数列的实例
Feb 25 Python
Python基于正则表达式实现计算器功能
Jul 13 Python
Python 使用office365邮箱的示例
Oct 29 Python
python小技巧——将变量保存在本地及读取
Nov 13 Python
Django使用django-simple-captcha做验证码的实现示例
Jan 07 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
php获取根域名方法汇总
2014/10/28 PHP
利用PHP判断文件是否为图片的方法总结
2017/01/06 PHP
php7性能提升的原因详解
2019/10/13 PHP
extjs 学习笔记 四 带分页的grid
2009/10/20 Javascript
Dom 是什么的详细说明
2010/10/25 Javascript
浅析JavaScript中的类型和对象
2013/11/29 Javascript
动态的绑定事件addEventListener方法的使用
2014/01/24 Javascript
JavaScript静态类型检查工具FLOW简介
2015/01/06 Javascript
javascript实现瀑布流自适应遇到的问题及解决方案
2015/01/28 Javascript
JS实现先显示大图后自动收起显示小图的广告代码
2015/09/04 Javascript
php利用curl获取远程图片实现方法
2015/10/26 Javascript
深入学习AngularJS中数据的双向绑定机制
2016/03/04 Javascript
jQuery简单创建节点的方法
2016/09/09 Javascript
JS中数组重排序方法
2016/11/11 Javascript
js仿搜狐视频记录片列表展示效果
2020/05/30 Javascript
在vue中使用jointjs的方法
2018/03/24 Javascript
Vue 路由切换时页面内容没有重新加载的解决方法
2018/09/01 Javascript
JS 正则表达式验证密码、邮箱格式的实例代码
2018/10/28 Javascript
JavaScript实现无限级递归树的示例代码
2019/03/29 Javascript
React中获取数据的3种方法及优缺点
2020/02/18 Javascript
python list转dict示例分享
2014/01/28 Python
Python cookbook(数据结构与算法)将名称映射到序列元素中的方法
2018/03/22 Python
python实现AES和RSA加解密的方法
2019/03/28 Python
详解Python sys.argv使用方法
2019/05/10 Python
使用pytorch 筛选出一定范围的值
2020/06/28 Python
基于zepto的插件之移动端无缝向上滚动并上下触摸滑动实例代码
2016/12/20 HTML / CSS
vivo智能手机官方商城:vivo
2016/09/22 全球购物
省三好学生申请材料
2014/01/22 职场文书
党风廉设责任书
2014/04/16 职场文书
优秀学生党员先进事迹材料
2014/05/29 职场文书
校园元旦活动总结
2014/07/09 职场文书
我爱祖国演讲稿
2014/09/02 职场文书
2014年党务工作总结
2014/11/25 职场文书
高中生综合素质自我评价
2015/03/06 职场文书
广播体操比赛主持词
2015/06/29 职场文书
详解Java七大阻塞队列之SynchronousQueue
2021/09/04 Java/Android