sort和sorted方法的使用
一、sorted()方法,接收两个参数,参数一: 可迭代对象,参数二:自定义字典的key,默认按升序排序
示例1:对列表进行排序:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
nums_list = [2,7,8,3,6,1,5,4] print(nums_list) print(id(nums_list)) # 1442097549832 x = sorted(nums_list) print(x) # [1, 2, 3, 4, 5, 6, 7, 8] print(id(x)) # 1442097550344 ,使用sorted排序后,会生成一个新列表
二、使用sort排序,使用匿名函数作为参数,对age进行排序
示例代码2:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
students = [ { 'name':'hw', 'age':19, 'score':88 }, { 'name':'lisa', 'age':18, 'score':100 }, { 'name':'yy', 'age':22, 'score':58 }, { 'name':'xx', 'age':28, 'score':39 } ] # 使用sort排序,使用匿名函数作为参数,对age进行排序 students.sort(key=lambda x:x['age']) print(students)
运行结果:
[{'name': 'lisa', 'age': 18, 'score': 100}, {'name': 'hw', 'age': 19, 'score': 88}, {'name': 'yy', 'age': 22, 'score': 58}, {'name': 'xx', 'age': 28, 'score': 39}]
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步