Python高階函式 sorted

2021-09-13 12:31:46 字數 1404 閱讀 8040

sorted函式是python的高階函式,是乙個排序的函式。

它和sort的主要區別在於,sort處理資料的時候並不會返回結果,而是將處理好的資料再次寫入到原來的列表中,而sorted函式處理完資料會將處理好的資料進行返回,並不會更改原來的列表。

sort處理列表:

l = [3,2,4,5,1,6]

l.sort()

print(l)

f:\學習**\python**\venv\scripts\python.exe f:/學習**/python**/day6/高階函式---sorted.py

[1, 2, 3, 4, 5, 6]

process finished with exit code 0

使用sorted函式處理:

l = [3,2,4,5,1,6]

res = sorted(l)

print(l)

print(res)

f:\學習**\python**\venv\scripts\python.exe f:/學習**/python**/day6/高階函式---sorted.py

[3, 2, 4, 5, 1, 6]

[1, 2, 3, 4, 5, 6]

process finished with exit code 0

對於列表中有正負值的時候,需要在呼叫sorted函式的時候新增key值: 

l = [-1,3,6,56,-23]

res = sorted(l)

print(l)

res1 = sorted(l,key=abs)

print(res1)

f:\學習**\python**\venv\scripts\python.exe f:/學習**/python**/day6/高階函式---sorted.py

[-1, 3, 6, 56, -23]

[-1, 3, 6, -23, 56]

process finished with exit code 0

對列表中的元素長度進行比較:

l = ["for","exit","break","continue",(1,2),,[1,2,3,4],"if"]

res = sorted(l,key=len)

print(res)

f:\學習**\python**\venv\scripts\python.exe f:/學習**/python**/day6/高階函式---sorted.py

[(1, 2), 'if', 'for', 'exit', [1, 2, 3, 4], 'break', 'continue', ]

process finished with exit code 0

Python 函式式程式設計 高階函式 sorted

排序也是在程式中經常用到的演算法。無論使用氣泡排序還是快速排序,排序的核心是比較兩個元素的大小。如果是數字,我們可以直接比較,但如果是字串或者兩個dict呢?直接比較數學上的大小是沒有意義的,因此,比較的過程必須通過函式抽象出來。print sorted 36,5,21,12,9,21 d anni...

python六十三課 高階函式之sorted

演示sorted函式的使用,以及和sort的區別 我們將sorted和sort進行一番比較 相同點 它們都是來實現排序的操作 功能層面 不同點 列表中的sort函式,它執行完畢後會直接影響原本這個list的內部結構 內部的資料發生改變了 而內建函式sorted函式,它執行完畢後不會影響原本容器中的內...

python 函式高階 python 函式高階

形參角度 萬能引數 動態接收位置引數 args 動態接收關鍵字引數 kwargs 的魔性用法 函式定義時 代表聚合。他將所有的位置引數 聚合成乙個元組,賦值給了args 函式定義時 將所有的關鍵字引數聚合成乙個字典中,將這個字典賦給了 kwargs 和 在函式的呼叫時 代表打散 僅限關鍵字引數 de...