**sorted函数** sorted 在Python3.5 中的源码,只摘录了下面咱们比较关注的部分 ~~~ def sorted(*args, **kwargs): # real signature unknown """ 默认返回一个包含所有排序元素的升序列表 Return a new list containing all items from the iterable in ascending order. 支持自定义键值方法的排序,并且可以设置逆序的标志将结果逆序。 A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order. """ pass ~~~ 排序在我们程序开发中是经常用到的功能。无论使用何种排序算法,排序的核心是比较两个元素的大小。如果是数字,我们可以直接比较,但如果不是数字呢?直接比较数学上的大小就没有意义了,因此,比较的过程必须通过函数抽象出来。 Python 内置的 sorted 方法对列表排序是非常强大的,我们通过下面几个例子来简单了解下。 实例 1:直接对数字列表排序 ~~~ >>> sorted([2,3,1,-1,0]) [-1, 0, 1, 2, 3] ~~~ 实例 2:自定义键值排序 ~~~ >>> sorted([2,3,1,-1,0],key=abs) [0, 1, -1, 2, 3] ~~~ 分析:sorted() 作为高阶函数,还可以接收一个 key 函数来实现自定义的排序,例如按绝对值大小排序,求绝对值的函数会作用在列表的每个元素上形成新的列表 keys,新的列表作为排序的依据,进行排序 ~~~ 原数据 [ 2 , 3 , 1 , -1 , 0 ] keys [ 2 , 3 , 1 , 1 , 0 ] ~~~ 按照 keys 进行升序排 ~~~ keys排序 [ 0 , 1 , 1 , 2 , 3 ] 最终结果 [ 0 , 1 , -1 , 2 , 3 ] ~~~ 实例 3:自定义键值排序并逆序 ~~~ >>> sorted([2,3,1,-1,0],key=abs,reverse=True) [3, 2, 1, -1, 0] ~~~ 实例 4 : 对字符串排序 ~~~ >>> sorted(['airvip','lucy','Pytohon','php']) ['Pytohon', 'airvip', 'lucy', 'php'] ~~~ 分析:默认情况下,对字符串排序,是按照 ASCII 码表的大小比较的,因为大写字母在小写字母前,所以大写字母开头的会排在小写字母开头的前面。 实例 5 :对列表中的元组按照元组的第二个值排序 ~~~ >>> L = [('b',1),('a',2),('d',3),('c',3)] >>> sorted(L,key=lambda x:x[1]) [('b', 1), ('a', 2), ('d', 3), ('c', 3)] ~~~ 我们看到,现在只是按照元组的第二个值排序,但我们还想按照元组中的第一个值排序,就需要 ~~~ >>> sorted(L,key=lambda x:(x[1],x[0])) [('b', 1), ('a', 2), ('c', 3), ('d', 3)] ~~~