排序与逆序
1. 排序函数sorted()
Python内置排序函数sorted()的说明如下
In [8]:sorted?
Signature: sorted(iterable, /, *, key=None, reverse=False)
Docstring:
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.
Type: builtin_function_or_method
使用sorted函数对一个可以排序的迭代对象进行排序,并且返回一个新列表(sorted操作不会更改原来的列表)。
参数
iterable:迭代对象
key:迭代依据,默认为None,即按照正常大小顺序排列
reverse:是否反转,默认为False,即按照升序排列
In [1]:x = list(range(12))
In [2]:import random
In [3]:random.shuffle(x)
In [4]:x
Out[4]: [7, 0, 9, 1, 8, 10, 2, 4, 11, 6, 3, 5]
In [5]:sorted(x)
Out[5]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
In [6]:sorted(x, reverse=True)
Out[6]: [11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
In [7]:x
Out[7]: [7, 0, 9, 1, 8, 10, 2, 4, 11, 6, 3, 5]
看看参数key的作用,一般来说,把一个匿名函数表达式赋值给参数key可以起到迭代依据的作用
In [19]: y = ['a', 'ba', 'ksml', 'bc', 'bcd', 'efg', 'edg', 'nnmm']
In [20]: sorted(y)
Out[20]: