轉自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的源代碼,能夠看這裏對象