Python 的排序方法 sort 和 sorted 的区别
2022-03-24 22:46
701 查看
使用
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、数据结构、算法、编程、网络等各种常考题。
相关文章推荐
- python进阶学习笔记-sort()方法和sorted()函数对列表内元素排序
- python 列表排序方法reverse、sort、sorted基础篇
- python 列表排序方法sort、sorted技巧篇
- python中sorted函数的详细使用方法及sort() 、sorted() 、与argsort()函数的区别
- python中的排序函数sorted以及列表排序方法sort()
- Python排序指南——sorted()函数和.sort()方法知识点汇总
- Python 列表排序方法reverse、sort、sorted详解
- python 中的排序方法:sorted() 和 sort()
- python中sort和sorted排序的实例方法
- Python 列表排序方法reverse、sort、sorted详解
- Python 列表排序方法reverse、sort、sorted详解
- python列表排序方法sort、sorted技巧篇
- python 中方法 sort() 和函数sorted()的区别!!!!
- python容器排序sort()和内建函数sorted()的区别
- python list排序sort和sorted的区别
- Python 列表排序方法reverse、sort、sorted操作方法
- Python 列表排序方法reverse、sort、sorted详解
- Python 列表排序方法reverse、sort、sorted详解
- Python 列表排序方法reverse、sort、sorted详解
- Python 列表排序方法reverse、sort、sorted详解