sorted函数
sorted函数是python的高阶函数,是一个排序的函数。
它和sort的主要区别在于,sort处理数据的时候并不会返回结果,而是将处理好的数据再次写入到原来的列表中,而sorted函数处理完数据会将处理好的数据进行返回,并不会更改原来的列表。
sort处理列表:
L = [3,2,4,5,1,6]
L.sort()
print(L)
F:\学习代码\Python代码\venv\Scripts\python.exe F:/学习代码/Python代码/day6/高阶函数---sorted.py
[1, 2, 3, 4, 5, 6]
Process finished with exit code 0
使用sorted函数处理:
L = [3,2,4,5,1,6]
res = sorted(L)
print(L)
print(res)
F:\学习代码\Python代码\venv\Scripts\python.exe F:/学习代码/Python代码/day6/高阶函数---sorted.py
[3, 2, 4, 5, 1, 6]
[1, 2, 3, 4, 5, 6]
Process finished with exit code 0
对于列表中有正负值的时候,需要在调用sorted函数的时候添加key值:
L = [-1,3,6,56,-23]
res = sorted(L)
print(L)
res1 = sorted(L,key=abs)
print(res1)
F:\学习代码\Python代码\venv\Scripts\python.exe F:/学习代码/Python代码/day6/高阶函数---sorted.py
[-1, 3, 6, 56, -23]
[-1, 3, 6, -23, 56]
Process finished with exit code 0
对列表中的元素长度进行比较:
L = ["for","exit","break","continue",(1,2),{1,2,3,4,5,6,7,8},[1,2,3,4],"if"]
res = sorted(L,key=len)
print(res)
F:\学习代码\Python代码\venv\Scripts\python.exe F:/学习代码/Python代码/day6/高阶函数---sorted.py
[(1, 2), 'if', 'for', 'exit', [1, 2, 3, 4], 'break', 'continue', {1, 2, 3, 4, 5, 6, 7, 8}]
Process finished with exit code 0