sort实现总成绩降序排列
时间: 2023-12-04 15:40:55 浏览: 57
以下是两种实现总成绩降序排列的方法:
1.使用sort()方法和自定义排序规则函数
```python
# 定义学生类
class Student:
def __init__(self, name, math, english, science):
self.name = name
self.math = math
self.english = english
self.science = science
def sum(self):
return self.math + self.english + self.science
# 定义排序规则函数
def sort_rule(student):
return student.sum()
# 创建学生列表
students = [Student('小明', 80, 90, 70), Student('小红', 90, 70, 80), Student('小刚', 70, 80, 90)]
# 对学生列表进行排序
students.sort(key=sort_rule, reverse=True)
# 输出排序结果
for student in students:
print(student.name, student.sum())
```
2.使用sort()方法和lambda表达式
```python
# 创建学生列表
students = [{'name': '小明', 'math': 80, 'english': 90, 'science': 70},
{'name': '小红', 'math': 90, 'english': 70, 'science': 80},
{'name': '小刚', 'math': 70, 'english': 80, 'science': 90}]
# 对学生列表进行排序
students.sort(key=lambda x: x['math'] + x['english'] + x['science'], reverse=True)
# 输出排序结果
for student in students:
print(student['name'], student['math'] + student['english'] + student['science'])
```