排序python
>>> z=[11,34,-12,9,8534,12,434] >>> z.sort() >>> z [-12, 9, 11, 12, 34, 434, 8534]
sort() 函數用於對原列表進行排序,若是指定參數,則使用比較函數指定的比較函數。dom
語法
sort()方法語法:ide
list.sort(cmp=None, key=None, reverse=False)
參數
參數
cmp -- 可選參數, 若是指定了該參數會使用該參數的方法進行排序。
key -- 主要是用來進行比較的元素,只有一個參數,具體的函數的參數就是取自於可迭代對象中,指定可迭代對象中的一個元素來進行排序。
reverse -- 排序規則,reverse = True 降序, reverse = False 升序(默認)。函數
>>> y [[3, 9], [1, 11], [5, 34], [2, 42], [4, 98]] >>> y=[[1,11],[2,42],[3,9],[4,98],[5,34]] >>> y.sort(key=lambda item:item[1]) >>> y [[3, 9], [1, 11], [5, 34], [2, 42], [4, 98]] >>>
>>> z=[{'id':'x1','length':13},{'id':'x2','length':201},{'id':'x3','length':98},{'id':'x4','length':9}] >>> z [{'id': 'x1', 'length': 13}, {'id': 'x2', 'length': 201}, {'id': 'x3', 'length': 98}, {'id': 'x4', 'length': 9}] >>> z.sort(key=lambda item: item.get('length')) >>> z [{'id': 'x4', 'length': 9}, {'id': 'x1', 'length': 13}, {'id': 'x3', 'length': 98}, {'id': 'x2', 'length': 201}] >>>
>>> z=[(1,"adsfafd"),(2,"qwer"),(3,"1234asf"),(4,"ew")] >>> z [(1, 'adsfafd'), (2, 'qwer'), (3, '1234asf'), (4, 'ew')] >>> z.sort(key=lambda ele:ele[1]) >>> z [(3, '1234asf'), (1, 'adsfafd'), (4, 'ew'), (2, 'qwer')] >>> z.sort(key=lambda ele:len(ele[1])) >>> z [(4, 'ew'), (2, 'qwer'), (3, '1234asf'), (1, 'adsfafd')] >>> z.sort(key=lambda ele:len(ele[1]),reverse=True) >>> z [(3, '1234asf'), (1, 'adsfafd'), (2, 'qwer'), (4, 'ew')]
多屬性排序code
>>> z=[(1,"adsfafd"),(2,"qwer"),(3,"1234asf"),(4,"ew"),(2,"24")] >>> z.sort(key=lambda ele:(len(ele[1]),ele[0])) >>> z [(2, '24'), (4, 'ew'), (2, 'qwer'), (1, 'adsfafd'), (3, '1234asf')] >>>
#!/usr/bin/python # 獲取列表的第二個元素 def takeSecond(elem): return elem[1] # 列表 random = [(2, 2), (3, 4), (4, 1), (1, 3)] # 指定第二個元素排序 random.sort(key=takeSecond) # 輸出類別 print ('排序列表:', random)