sort函数
原地排序,直接改变输入的列表,而无返回值。
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]
sort函数的关键字参数
- cmp: 可以自定义比较参数。cmp(x,y)在x小于y时返回负数,在x大于y时返回正数,在x等于y时返回0。
print cmp(1, 2)
# output: -1
print cmp(1, 1)
# output: 0
print cmp(2, 1)
# output: 1
x = [2, 1, 3]
x.sort(cmp)
print x
# output: [1, 2, 3]
- key: 根据键值排序。
x = ['aaa', 'a', 'aa']
x.sort(key=len)
print x
# output: ['a', 'aa', 'aaa']
- reverse: 表明列表是否要进行反向排序。
x = [2, 1, 3]
x.sort(reverse=True)
print x
# output: [3, 2, 1]
sorted函数
sorted函数能实现上述不改变待排列表,并返回排序副本的需求。
x = [2, 1, 3]
y = sorted(x)
print x
# output: [2, 1, 3]
print y
# output: [1, 2, 3]