python內建的 sorted()函式可對list進行排序:
>>>sorted([36, 5, 12, 9, 21])[5, 9, 12, 21, 36]
但 sorted()也是一個高階函式,它可以接收一個比較函式來實現自定義排序,比較函式的定義是,傳入兩個待比較的元素 x, y,如果 x 應該排在 y 的前面,返回 -1,如果 x 應該排在 y 的後面,返回 1。如果 x 和 y 相等,返回 0。
因此,如果我們要實現倒序排序,只需要編寫一個reversed_cmp函式:
defreversed_cmp(x, y):
if x >y:
return -1
if x return 1
return 0
這樣,呼叫 sorted() 並傳入 reversed_cmp 就可以實現倒序排序:
>>> sorted([36, 5, 12, 9, 21], reversed_cmp)[36, 21, 12, 9, 5]
sorted()也可以對字串進行排序,字串預設按照ascii大小來比較:
>>> sorted(['bob', 'about', 'zoo', 'credit'])'zoo'排在'about'之前是因為'z'的ascii碼比'a'小。['credit', 'zoo', 'about', 'bob']
練習:
對字串排序時,有時候忽略大小寫排序更符合習慣。請利用sorted()高階函式,實現忽略大小寫排序的演算法。
輸入:['bob', 'about', 'zoo', 'credit']
>>> a = ['bob', 'about', 'zoo', 'credit']
>>> print(sorted(a, key=str.lower))
結果:
['about
', '
bob', '
credit
', '
zoo']
python之自定義排序函式sorted
sorted 也是一個高階函式,它可以接收一個比較函式來實現自定義排序,比較函式的定義是,傳入兩個待比較的元素 x y,如果 x 應該排在 y 的前面,返回 1,如果 x 應該排在 y 的後面,返回 1。如果 x 和 y 相等,返回 0。 def custom sort x y if x y ret...
python中陣列物件排序
sort 方法語法 list sort cmp none key none reverse false 引數 例子1 usr bin python coding utf 8 獲取列表的第二個元素 def takesecond elem return elem 1 列表 random 2 2 3 4 ...
python字典實現按照自定義順序排序
還是對於python字典理解不透徹,試圖通過sort來給python的key指定順序,幾經試驗,仍然得不到想要的效果,後來一想,python...