sorted排序函數
阿新 • • 發佈:2018-08-15
turn key 叠代 進行 spa lam 可叠代對象 一起 als
排序函數
語法:sorted(Iterable,key=None,reverse=False)
Iterable:可叠代對象
key:排序規則(排序函數),在sorted內部會將可叠代對象中的每一個元素傳遞給這個函數的參數,根據函數運算的結果進行排序
reverse:是否是倒敘. True:倒敘,False:正序
lst = [1,5,6,4,3] new_lst = sorted(lst) print(lst) #原列表不會變 print(new_lst) #新列表是從小到大排序
lst = ["麻花藤", "岡本次郎", "中央情報局", "狐仙"] print(sorted(lst,key=lambdas:len(s))) #還可以和lamda一起用
dic = {1:"a",3:"b",2:"c"} dic1 = sorted(dic) print(dic1) #如果是字典,返回排序後的key
lst = ["麻花藤", "岡本次郎", "中央情報局", "狐仙"] def func(s): return len(s) print(sorted(lst,key = func)) #還可以和函數一起用,按字符串長度排序
sorted排序函數