通常,我们排序的时候,我们可以使用系统内置的sorted函数或list自带的sort函数。
参考文章:http://www.jb51.net/article/57678.htm
https://docs.python.org/3/library/stdtypes.html?highlight=sort#list.sort
1. list.sort
sort(*, key=None, reverse=False)This method sorts the list in place, using only < comparisons between items. Exceptions are not suppressed - if any comparison operations fail, the entire sort operation will fail (and the list will likely be left in a partially modified state).
sort是就地排序
key可以传入一个函数,会作用于每一个element,返回值会作为排序键
key specifies a function of one argument that is used to extract a comparison key from each list element (for example, key=str.lower). The key corresponding to each item in the list is calculated once and then used for the entire sorting process. The default value of None means that list items are sorted directly without calculating a separate key value.
|
|
2. sorted
sorted(iterable, *, key=None, reverse=False)Return a new sorted list from the items in iterable
sorted是返回一个排序后的新list,使用方式基本一样,只是
sorted方法对所有的可迭代对象都有效
使用sorted还能对复杂对象进行排序
对于自定义的对象也是可以的