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

python中sort和sorted的区别

作者:天盟丶阎王   发布日期:2026-07-10   浏览:58

# 示例代码:Python中sort和sorted的区别

# sort 是列表对象的方法,它会原地排序列表,返回值为None
my_list = [3, 1, 2]
my_list.sort()
print(my_list)  # 输出: [1, 2, 3]

# sorted 是内置函数,它不会修改原始列表,而是返回一个新的已排序列表
original_list = [3, 1, 2]
new_sorted_list = sorted(original_list)
print(original_list)  # 输出: [3, 1, 2]
print(new_sorted_list)  # 输出: [1, 2, 3]

# sort 可以通过传递 key 参数来自定义排序规则
words = ['apple', 'banana', 'cherry']
words.sort(key=len)
print(words)  # 输出: ['apple', 'cherry', 'banana']

# sorted 同样支持 key 参数
words = ['apple', 'banana', 'cherry']
sorted_words = sorted(words, key=len)
print(sorted_words)  # 输出: ['apple', 'cherry', 'banana']

上一篇:python len函数

下一篇:python列表倒序

大家都在看

python 二维码识别

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

python集合中的元素可以是列表

staticmethod在python中有

python 保存json文件

python的assert基本用法

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

Laravel 中文站