>>> help(list.sort)
Help on method_descriptor:
sort(...)
L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
1.sort()对列表进行原址排序
a=[2,3,2,5,6,8,9,0,1,6,7,12] a.sort() print(a) >>>[0, 1, 2, 2, 3, 5, 6, 6, 7, 8, 9, 12]
2.key参数
a=['aaa','aaaa','a','aa'] a.sort(key=len) print(a) >>>['a', 'aa', 'aaa', 'aaaa']
参数为函数
#要求1.正数在前负数在后 2.正数从小到大 3.负数从大到小 a=[7,3, -8, 5, 4, 0, -2, -5] a.sort(key=lambda x:(x<0,abs(x))) print(a) >>>[0, 3, 4, 5, 7, -2, -5, -8]
3.reverse参数:是否要对列表进行反向排序,默认Falses升序
a=[7,3, -8, 5, 4, 0, -2, -5] b=a[:] a.sort() b.sort(reverse=True) print(a) print(b) >>> [-8, -5, -2, 0, 3, 4, 5, 7] [7, 5, 4, 3, 0, -2, -5, -8]