2.2 创建一个Score类,完成以下功能: ■连续输入多位学生的成绩(成绩=科目A成绩+科目B成绩+科目C成绩); ■学生数目可以由用户自定义(默认为2个,最多为100个); ■显示每位同学的每科成绩和平均分; ■显示每门科目的平均成绩; ■对每门成绩进行排序并由高到底显示;
时间: 2024-10-21 19:04:02 浏览: 18
创建一个名为`Score`的类来满足上述需求,我们可以设计如下的结构:
```python
class Score:
def __init__(self, num_students=2, max_students=100):
self.students = [Student()] * min(num_students, max_students)
def input_scores(self):
for i in range(len(self.students)):
print(f"请输入第{i + 1}名同学的成绩 (格式:A B C):")
scores_str = input().split()
self.students[i].set_scores(float(scores_str[0]), float(scores_str[1]), float(scores_str[2]))
def display_student_info(self):
for student in self.students:
print(f"学生{student.id}:")
print(f"科目A: {student.score_a}, 科目B: {student.score_b}, 科目C: {student.score_c}")
avg_score = sum(student.scores) / len(student.scores)
print(f"平均分: {avg_score}")
def display_subject_average(self):
subject_totals = {'A': 0., 'B': 0., 'C': 0.}
for student in self.students:
for subject, score in zip('ABC', student.scores):
subject_totals[subject] += score
for subject, total in subject_totals.items():
avg = total / len(self.students)
print(f"{subject}科目平均分: {avg}")
def sort_and_display_scores(self, by='total'):
if by == 'total':
sorted_students = sorted(self.students, key=lambda s: s.total_score, reverse=True)
elif by == 'average':
sorted_students = sorted(self.students, key=lambda s: s.avg_score, reverse=True)
else:
raise ValueError("排序依据只能是'total'或'average'")
print("\n按照{}排序后的成绩:".format(by))
for i, student in enumerate(sorted_students):
print(f"第{i + 1}名: {student.name}, 总分: {student.total_score}, 平均分: {student.avg_score}")
class Student:
def __init__(self, id=1):
self.name = f"学生{id}"
self.scores = ['A', 'B', 'C']
self.score_a, self.score_b, self.score_c = 0., 0., 0.
self.total_score = 0.
self.avg_score = 0.
def set_scores(self, a, b, c):
self.score_a, self.score_b, self.score_c = a, b, c
self.total_score = a + b + c
self.avg_score = self.total_score / 3
# 示例
score_system = Score()
score_system.input_scores()
score_system.display_student_info()
score_system.display_subject_average()
score_system.sort_and_display_scores()
```
这个`Score`类包含了所需的功能,包括输入学生成绩、显示信息、计算平均分、显示科目平均分以及按总分或平均分排序。
阅读全文