一、列表排序
1.1 列表排序list.sort,改变原始列表的顺序,reverse按降序排列
list.sort(key=None, reverse=False)
如下:所有学生成绩,按数学成绩排序
students = [{"name":"zhangsan1","math":"89","english":"87"},
{"name":"zhangsan2","math":"65","english":"87"},
{"name":"zhangsan3","math":"99","english":"87"},
{"name":"zhangsan4","math":"55","english":"87"},
]
students.sort(key=lambda item: item.get('math'),reverse=True)
print(students)
1.2 列表排序sorted,不改变原始列表或字典的顺序,返回一个新的列表
sorted(iterable, key=None, reverse=False)
所有学生成绩,按数学成绩排序
students = [{"name":"zhangsan1","math":"89","english":"87"},
{"name":"zhangsan2","math":"65","english":"87"},
{"name":"zhangsan3","math":"99","english":"87"},
{"name":"zhangsan4","math":"55","english":"87"},
]
result = sorted(students, key=lambda student:student['math'], reverse=True)
print(result)
print(students)
二、字典排序
2.1字典排序sorted,按key大小排序,返回一个元组,原始字典顺序不变
单个学生按分数排序的各科目
zhangsan = {"math":"89","english":"87","chinese":"99"}
result = sorted(zhangsan.items(), key=lambda item:item[1],reverse=True)
print(result)
print(zhangsan)