原地排序,直接改变输入的列表,而无返回值。
x = [2, 1, 3] x.sort() print x # output: [1, 2, 3] print x.sort() # output: None若要实现赋值,则先把x的副本(一个新对象)赋值给一个变量,再排序,这样可以保证不改变x。
x = [2, 1, 3] y = x[:] # 或 y = list(x) y.sort() print x # output: [2, 1, 3] print y # output: [1, 2, 3]若直接赋值,不新建对象,实际上传递的是x的地址,x和y最后会指向同一对象,导致x和y都改变。
x = [2, 1, 3] y = x y.sort() print x # output: [1, 2, 3] print y # output: [1, 2, 3]sorted函数能实现上述不改变待排列表,并返回排序副本的需求。
x = [2, 1, 3] y = sorted(x) print x # output: [2, 1, 3] print y # output: [1, 2, 3]