Manual
Return a new sorted list from the items in iterable.
Has two optional arguments which must be specified as keyword arguments.
key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).
reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.
Use functools.cmp_to_key() to convert an old-style cmp function to a key function.
The built-in sorted() function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).
For sorting examples and a brief sorting tutorial, see Sorting HOW TO.
直译
根据iterable中的项返回一个新排序的列表。
这里有两个可选参数,其必须指定为关键字参数。
- key指定某个参数的函数,它可以用于从每个列表元素中提取比较键,例如key=str.lower。默认值为None(直接比较元素)。
- reverse是一个布尔值,如果设置为True,列表的元素会将每个比较反置进行排列。
内建sorted()函数可以保证稳定,如果它保证不改变元素的相对顺序,那么排序就是稳定的。相对顺序的比较恒等,对于多次传递下的排序很有用(例如:按部门排序,然后按工资等级排序)
实例
实例摘自官方手册
基本排序
# 简单排序
>>> sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]
# list.sort()方法,该方法仅对列表定义。
>>> a = [5, 2, 3, 1, 4]
>>> a.sort()
>>> a
[1, 2, 3, 4, 5]
# sorted()支持任何迭代形式
>>> sorted({
1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
[1, 2, 3, 4, 5]
key函数
list.sort()和sorted()都有key参数,用来指定一个函数,并对每个列表元素对象调用该函数进行比较。
# 小写字符串比较,key=str.lower
>>> sorted("This is a test string from Andrew".split(), key=str.lower)
['a', 'Andrew',