欢迎访问宙启技术站
智能推送

sort、sorted函数在Python中的区别及其用法

发布时间:2023-07-15 22:56:04

sort和sorted函数都可以用于对序列进行排序操作,但是它们的使用方式和特点有所不同。

sort函数是列表的成员函数,直接对原始列表进行排序,不会创建新的列表副本。sort函数会修改原始列表,使得原始列表中的元素按照指定的排序方式重新排列。sort函数没有返回值,调用该函数后,原始列表被修改排序。sort函数默认使用升序排序,也可以通过reverse参数指定为降序排序。例如:

lst = [3, 1, 4, 1, 5, 9, 2, 6, 5, 4]
lst.sort()
print(lst)  # 输出 [1, 1, 2, 3, 4, 4, 5, 5, 6, 9]

若要实现降序排序,可以使用sort函数的reverse参数,将其设置为True:

lst.sort(reverse=True)
print(lst)  # 输出 [9, 6, 5, 5, 4, 4, 3, 2, 1, 1]

sorted函数是Python内置的全局函数,对于任意序列(如列表、元组、字符串等)都可以使用,它返回一个新的列表,原始序列保持不变。sorted函数不会修改原始序列,而是创建一个新的已排序的列表。sorted函数的 个参数为待排序的序列,第二个参数为可选参数,用于指定排序方式(升序或降序),默认值为升序。例如:

lst = [3, 1, 4, 1, 5, 9, 2, 6, 5, 4]
new_lst = sorted(lst)
print(new_lst)  # 输出 [1, 1, 2, 3, 4, 4, 5, 5, 6, 9]
print(lst)  # 输出 [3, 1, 4, 1, 5, 9, 2, 6, 5, 4]

与sort函数一样,sorted函数的reverse参数可以用来指定排序方式为降序:

new_lst = sorted(lst, reverse=True)
print(new_lst)  # 输出 [9, 6, 5, 5, 4, 4, 3, 2, 1, 1]

总结起来,sort函数和sorted函数都可以用于排序操作,sort函数是列表的成员函数,直接对原始列表进行排序,不会返回新的列表。sorted函数是Python内置的全局函数,对于任意序列都可以使用,它会创建一个新的已排序的列表,不会修改原始序列。