# 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中集合
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站