a=[1, 3, 2, 5].sort() --- a结果为None

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 函数时,需要注意这两个函数并没有返回结果,而是直接改变自身。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容