內置函數——sorted


對List、Dict進行排序,Python提供了兩個方法
對給定的List L進行排序,
方法1.用List的成員函數sort進行排序,在本地進行排序,不返回副本
方法2.用built-in函數sorted進行排序(從2.4開始),返回副本,原始輸入不變

--------------------------------sorted---------------------------------------

sorted(iterable, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.

A custom key function can be supplied to customise the sort order, and the
reverse flag can be set to request the result in descending order.


-----------------------------------------------------------------------------
參數說明:
iterable:是可迭代類型;
key:傳入一個函數名,函數的參數是可迭代類型中的每一項,根據函數的返回值大小排序;
reverse:排序規則. reverse = True  降序 或者 reverse = False 升序,有默認值。
返回值:有序列表
 
例:
列表按照其中每一個值的絕對值排序
l1 = [1,3,5,-2,-4,-6]
l2 = sorted(l1,key=abs)
print(l1)
print(l2)
列表按照絕對值排序

 

列表按照每一個元素的len排序

l = [[1,2],[3,4,5,6],(7,),'123']
print(sorted(l,key=len))
列表按照每一個元素的長度排序

 

 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM