18、怎样实现学生成绩排序
题目:
学生成绩数据格式:
- 复杂列表,元素是字典或者元组。
- [
{'id':101,'name':"小周",'grade':88},
{'id':102,'name':"小吴",'grade':73},
{'id':103,'name':"小郑",'grade':96},
{'id':104,'name':"小王",'grade':60},
- ]
思路:
1、运用sorted()方法
2、在字典中在键上运用lambda函数,传递grade参数即可。
结果:
- 降序排序。
student = [
{'id':101,'name':"小周",'grade':88},
{'id':102,'name':"小吴",'grade':73},
{'id':103,'name':"小郑",'grade':96},
{'id':104,'name':"小王",'grade':60},
]
student_sort = sorted(student,key=lambda x:x["grade"],reverse=True)
print(student_sort)
----------------------------------
[{'id': 103, 'name': '小郑', 'grade': 96}, {'id': 101, 'name': '小周', 'grade': 88}, {'id': 102, 'name': '小吴', 'grade': 73}, {'id': 104, 'name': '小王', 'grade': 60}]
- 升序排序
student = [
{'id':101,'name':"小周",'grade':88},
{'id':102,'name':"小吴",'grade':73},
{'id':103,'name':"小郑",'grade':96},
{'id':104,'name':"小王",'grade':60},
]
student_sort = sorted(student,key=lambda x:x["grade"],reverse=False)
print(student_sort)
---------------------------------------
[{'id': 104, 'name': '小王', 'grade': 60}, {'id': 102, 'name': '小吴', 'grade': 73}, {'id': 101, 'name': '小周', 'grade': 88}, {'id': 103, 'name': '小郑', 'grade': 96}]