對List、Dict進行排序,Python提供了兩個方法
對給定的List L進行排序,
方法1.用List的成員函數sort進行排序,在本地進行排序,不返回副本
方法2.用built-in函數sorted進行排序(從2.4開始),返回副本,原始輸入不變
--------------------------------sorted---------------------------------------
-----------------------------------------------------------------------------
參數說明:
iterable:是可迭代類型;
key:傳入一個函數名,函數的參數是可迭代類型中的每一項,根據函數的返回值大小排序;
reverse:排序規則. reverse = True 降序 或者 reverse = False 升序,有默認值。
返回值:有序列表
對給定的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))