a = [1, 3, 2, 5]
b = a.sort()
b 为 None
关于官方的解释:
5.6.4. Mutable Sequence Types
s.reverse() reverses the items of s in place
Note:The sort() and reverse() methods modify the list in place for economy of space when sorting or reversing a large list. To remind you that they operate by side effect, they don’t return the sorted or reversed list.
其实意思就是:sort() 和 reverse() 函数直接改变自身,是为了节省内存。并没有返回值。所以,在ipython中执行后,结果如下:
In [27]: a = [1, 3, 6, 2, 7, 4]
In [28]: a.reverse()
In [29]: a
Out[29]: [4, 7, 2, 6, 3, 1]
总结:在使用列表的 sort 和 reverse 函数时,需要注意这两个函数并没有返回结果,而是直接改变自身。