Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python sort和sorted的区别

作者:Haggard憔悴   发布日期:2026-05-04   浏览:86

# Python sort 和 sorted 的区别

# sort 是列表对象的方法,它会直接修改原列表并对其进行排序
# 示例:
list1 = [3, 1, 4, 1, 5, 9]
list1.sort()
print(list1)  # 输出: [1, 1, 3, 4, 5, 9]

# sorted 是内置函数,它不会修改原列表,而是返回一个新的已排序的列表
# 示例:
list2 = [3, 1, 4, 1, 5, 9]
sorted_list2 = sorted(list2)
print(list2)         # 输出: [3, 1, 4, 1, 5, 9]
print(sorted_list2)  # 输出: [1, 1, 3, 4, 5, 9]

# sort 和 sorted 都可以接受可选参数 reverse=True 来进行降序排序
# 示例:
list3 = [3, 1, 4, 1, 5, 9]
list3.sort(reverse=True)
print(list3)  # 输出: [9, 5, 4, 3, 1, 1]

list4 = [3, 1, 4, 1, 5, 9]
sorted_list4 = sorted(list4, reverse=True)
print(list4)         # 输出: [3, 1, 4, 1, 5, 9]
print(sorted_list4)  # 输出: [9, 5, 4, 3, 1, 1]

上一篇:python reduce函数

下一篇:python中集合

大家都在看

python 二维码识别

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

staticmethod在python中有

python 保存json文件

python的assert基本用法

python开发windows应用程序

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站