Python sorted函数详解(高级篇)

yipeiwu_com5年前Python基础

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 性能优化技巧总结

1.使用测量工具,量化性能才能改进性能,常用的timeit和memory_profiler,此外还有profile、cProfile、hotshot等,memory_profiler用了...

python多进程读图提取特征存npy

本文实例为大家分享了python多进程读图提取特征存npy的具体代码,供大家参考,具体内容如下 import multiprocessing import os, time, ran...

django 邮件发送模块smtp使用详解

前言 在Python中已经内置了一个smtp邮件发送模块,Django在此基础上进行了简单地封装,让我们在Django环境中可以更方便更灵活的发送邮件。 所有的功能都在django.co...

Python 命令行非阻塞输入的小例子

 随手google咗一下,基本上都用select实现非阻塞监听,但问题是,监听的是用select之后是不能像getchar()那样,即时收到单个字符的输入,必须要等待回车。 &...

全面解析Python的While循环语句的使用方法

全面解析Python的While循环语句的使用方法

Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。其基本形式为: while 判断条件: 执行语句……...