今天在编写代码时,在使用sort方法对序列进行排序时,遇到了一些特殊情况,才知道有这些坑
正确使用sort方法对序列进行排序:
arr = [2, 3, 67, 5, 56, 25, 56, 65]
# 对序列arr进行排序
print(arr.sort())
print(arr)
运行结果为:
需要注意的是:调用sort方法是没有返回值的,它是在内存中对可变序列进行排序
接下来就是错误的用法了:
在调用sort之前,去调用其他的方法,运行时就会报错
arr = [2, 3, 67, 5, 56, 25, 56, 65]
arr.remove(5).sort()
print(arr)
运行结果为:
不只是调用remove,调用其他的基本上都会出现同样的问题:
arr = [2, 3, 67, 5, 56, 25, 56, 65]
try:
arr.append(6).sort()
print(arr)
except Exception as e:
print(e)
try:
arr.index(5).sort()
print(arr)
except Exception as e:
print(e)
运行结果为:
因此在使用sort方法时需要注意