输入3个学生3门课的成绩,分别用函数实现下列功能: ①计算每个学生平均分; ②计算每门课的平均分; ③找出所有9个分数中最高的分数所对应的学生和课程。
时间: 2024-12-18 12:31:39 浏览: 11
首先,我们可以创建一个名为`Student`的类,包含姓名和三个成绩属性。然后,我们定义两个辅助函数,用于计算单个学生的平均分和一门课程的所有学生的平均分。最后,我们会创建一个函数来找出最高分及其对应的学生成绩。
```python
class Student:
def __init__(self, name):
self.name = name
self.grades = [0, 0, 0] # 学生的三门课成绩
def calculate_student_average(student):
return sum(student.grades) / len(student.grades)
def calculate_subject_average(students):
subject_averages = {i: [] for i in range(1, 4)} # 三门课的列表
for student in students:
for subject_index, grade in enumerate(student.grades):
subject_averages[subject_index].append(grade)
return {k: sum(v) / len(v) for k, v in subject_averages.items()}
def find_highest_score(students):
highest_score = max(student.grades for student in students)
max_students_and_courses = [(student, subject_index, score) for student in students for subject_index, score in enumerate(student.grades) if score == highest_score]
return max_students_and_courses
# 示例用法
students = [Student('张三'), Student('李四'), Student('王五')]
students[0].grades = [85, 90, 92]
students[1].grades = [88, 89, 91]
students[2].grades = [90, 87, 93]
average_students = [calculate_student_average(student) for student in students]
average_subjects = calculate_subject_average(students)
highest_score_info = find_highest_score(students)
print("学生平均分:", average_students)
print("各科平均分:", average_subjects)
print("最高分及对应学生和课程:", highest_score_info)
```
在这个例子中,我们通过函数实现了计算学生平均分、科目平均分以及找出最高分的功能。每个学生都有自己的成绩列表,我们可以轻松地遍历和分析这些数据。
阅读全文