转自http://longriver.me/?p=325python
常用python built-in sort 方法,使用方法例子以下:算法
1
2
3
4
|
alist
=
[
1
,
2
,
3
,
4
,
5
,
6
,
7
]
blist
=
sorted
(
alist
,
key
=
lambda
ele
:
ele
,
reverse
=
True
)
print
blist
[
7
,
6
,
5
,
4
,
3
,
2
,
1
]
|
Sorted 方法用起来很方便,当alist的元素是个对象的时候能够本身定义对对象的排序,如svn
1
|
sorted
(
nb_stats
,
key
=
lambda
stat
:
10
*
len
(
stat
.
night_day
)
+
len
(
stat
.
day
)
,
reverse
=
True
)
|
有的时候咱们须要连续使用sorted对list的elements作屡次排序,这样就须要考虑python 内置的sorted 的稳定性问题:ui
In early python-versions, the sort function implemented a modified version of quicksort. However, it was deemed unstable and as of 2.3 they switched to using an adaptive mergesort algorithm.spa
可见早期的sort实现的是quicksort,是不稳定,到了python2.3以后,改为了适应性的归并排序算法,是稳定算法了。code
若是想看sort的源代码,能够看这里对象