Python高阶函数---sorted

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值