使用 sort()
或内建函数 sorted()
对列表进行排序。它们之间的区别有两点:
sort()
方法是对原列表进行操作,而sorted()
方法会返回一个新列表,不是在原来的基础上进行操作。sort()
是应用在列表上的方法,而sorted()
可以对所有可迭代的对象进行排序操作。
sort()
>>> a = [1, 2, 3, 4, 2, 3]
>>> a.sort()
>>> a
[1, 2, 2, 3, 3, 4]
>>>
>>> a = [1, 2, 3, 4, 2, 3]
>>> a.sort(reverse=True)
>>> a
[4, 3, 3, 2, 2, 1]
sorted()
>>> a = [1, 2, 3, 4, 2, 3]
>>> sorted(a)
[1, 2, 2, 3, 3, 4]
>>> a = [1, 2, 3, 4, 2, 3]
>>> sorted(a, reverse=True)
[4, 3, 3, 2, 2, 1]
以上就是本文的全部内容,如果觉得还不错的话,欢迎 点赞, 转发和 关注,感谢支持。
推荐阅读:
- 计算机经典书籍
- 技术博客 : 硬核后端开发技术干货,内容包括 Python、Django、Docker、Go、Redis、ElasticSearch、Kafka、Linux 等。
- Go 程序员 : Go 学习路线图,包括基础专栏,进阶专栏,源码阅读,实战开发,面试刷题,必读书单等一系列资源。
- 面试题汇总 : 包括 Python、Go、Redis、MySQL、Kafka、数据结构、算法、编程、网络等各种常考题。
Original: https://www.cnblogs.com/alwaysbeta/p/16052432.html
Author: yongxinz
Title: Python 的排序方法 sort 和 sorted 的区别
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/814646/
转载文章受原作者版权保护。转载请注明原作者出处!