写一个班级成绩排序程序。班级有班级号,班级人数和若干学生,每个学生有学号、姓名、三门课成绩。按学生总成绩从高到底进行排序。
时间: 2023-12-03 19:46:08 浏览: 228
以下是一个Python程序,用于对班级成绩进行排序:
```python
class Student:
def __init__(self, id, name, score1, score2, score3):
self.id = id
self.name = name
self.score1 = score1
self.score2 = score2
self.score3 = score3
self.total = score1 + score2 + score3
class Class:
def __init__(self, class_id, num_of_students):
self.class_id = class_id
self.num_of_students = num_of_students
self.students = []
def add_student(self, id, name, score1, score2, score3):
student = Student(id, name, score1, score2, score3)
self.students.append(student)
def sort_students_by_total_score(self):
self.students.sort(key=lambda x: x.total, reverse=True)
def print_students(self):
print("Class ID:", self.class_id)
print("Number of students:", self.num_of_students)
print("Sorted students by total score:")
for student in self.students:
print("ID:", student.id, "Name:", student.name, "Total score:", student.total)
# Example usage
my_class = Class("A001", 3)
my_class.add_student("S001", "Alice", 90, 80, 70)
my_class.add_student("S002", "Bob", 80, 70, 60)
my_class.add_student("S003", "Charlie", 70, 60, 50)
my_class.sort_students_by_total_score()
my_class.print_students()
```
上述程序定义了一个`Student`类和一个`Class`类。`Student`类用于保存学生的信息,包括学号、姓名和三门课成绩,以及总成绩。`Class`类用于保存班级的信息,包括班级号、人数和学生列表。它还提供了添加学生和按总成绩排序的方法。
在示例用法中,我们创建了一个班级对象,并添加了三个学生。然后,我们按总成绩对学生进行排序,并打印学生列表。
阅读全文