python中几种常见的排序方法以及详细讲解?
sort
: 对列表排序,但没有返回值。
x = [4, 6, 2, 7, 1, 9] y = x.sort() # sort方法没有返回值,这一操作是错误的! print(y) >>> None # 正确操作为: y = x.copy() y.sort() x >>> [4, 6, 2, 7, 1, 9] y >>> [1, 2, 4, 6, 7, 9]
sorted()
: 这个方法可以返回新的列表
y = sorted(x) x >>> [4, 6, 2, 7, 1, 9] y >>> [1, 2, 4, 6, 7, 9]
sort
还可以接受两个可选参数,key
&reverse
x.sort(key=len) x >>> ['re', 'asd', 'qweqwe', 'asdfasd', 'eqweqwrqw'] x.sort(key=len, reverse=True) x >>> ['eqweqwrqw', 'asdfasd', 'qweqwe', 'asd', 're']
原文链接:https://blog.csdn.net/leeyns/article/details/106169733