代码:
students=[ {"sno":101,"sname":"刘晨曦","sgrade":88}, {"sno":102,"sname":"王雨轩","sgrade":98}, {"sno":103,"sname":"王祎伟","sgrade":90}, {"sno":104,"sname":"李威","sgrade":70}, {"sno":105,"sname":"景少帅","sgrade":99}, {"sno":106,"sname":"周泽宇","sgrade":96}, ] students_sort=sorted(students, key=lambda x:x["sgrade"], reverse=True) print(f"Source list:{students}") print(f"Sort result:{students_sort}")
效果:
Source list:[{'sno': 101, 'sname': '刘晨曦', 'sgrade': 88}, {'sno': 102, 'sname': '王雨轩', 'sgrade': 98}, {'sno': 103, 'sname': '王祎伟', 'sgrade': 90}, {'sno': 104, 'sname': '李威', 'sgrade': 70}, {'sno': 105, 'sname': '景少帅', 'sgrade': 99}, {'sno': 106, 'sname': '周泽宇', 'sgrade': 96}] Sort result:[{'sno': 105, 'sname': '景少帅', 'sgrade': 99}, {'sno': 102, 'sname': '王雨轩', 'sgrade': 98}, {'sno': 106, 'sname': '周泽宇', 'sgrade': 96}, {'sno': 103, 'sname': '王祎伟', 'sgrade': 90}, {'sno': 101, 'sname': '刘晨曦', 'sgrade': 88}, {'sno': 104, 'sname': '李威', 'sgrade': 70}]
总结:
- 列表里面插入了字典元素,list里面元素用,号隔开,字典元素放在{}里面,里面的元素也是用,号隔开;
- 列表元素都可以用sorted函数进行排序;
- key=lambda x:x["grade"]函数,返回列表grade字段作为索引;
- desc需要用到reverse=True。