参考:
列表排序有两种方法实现,一种是列表自带的sort()方法,即list.sort(),另一种则是通过sorted()进行排序。
sort()方法语法:
list.sort(key=None, reverse=False)
该方法没有返回值,会改变原始列表的顺序。
sorted()语法:
sorted(iterable, key=None, reverse=False)
返回一个新的列表。
可以使用sorted()函数和lambda表达式对学生信息的列表进行按总成绩排序,然后输出新的列表。
假设学生信息是以字典形式存储的,字典的key包括"name"、"score1"、"score2"、"score3",分别表示学生的姓名、第一门课的成绩、第二门课的成绩、第三门课的成绩。以下是实现代码:
students = [{"name": "Tom", "score1": 80, "score2": 90, "score3": 70},
{"name": "John", "score1": 70, "score2": 85, "score3": 90},
{"name": "Amy", "score1": 90, "score2": 80, "score3": 85},
{"name": "Lucy", "score1": 85, "score2": 75, "score3": 95}]
# 使用lambda表达式来定义排序规则
sorted_students = sorted(students, key=lambda x: x["score1"] + x["score2"] + x["score3"], reverse=True)
# 输出排序后的结果
for student in sorted_students:
print(student)
上述代码会将学生信息按照总成绩从高到低进行排序,然后输出排序后的结果。其中,sorted()函数的key参数使用了lambda表达式来定义排序规则,即按照总成绩进行排序。reverse参数设置为True表示按照降序排序。