# 示例代码: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列表倒序
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站