统计scores数组中每位同学所有科目的平均值用python
时间: 2024-11-14 09:22:51 浏览: 21
在Python中,我们可以使用字典来存储每个学生及其对应的科目分数,然后遍历字典计算平均分。这里是一个简单的示例:
```python
# 假设我们有这样一个scores数组,包含学生ID、姓名和各科成绩
scores = [
{"id": "001", "name": "小明", "math": 95, "english": 88, "science": 92},
{"id": "002", "name": "小红", "math": 80, "english": 90, "science": 85},
# 更多学生数据...
]
# 创建一个空字典来存储每个学生的总分和科目数
students_scores = {}
# 遍历scores数组,累加每个学生每门课的成绩并记录科目数
for student in scores:
student_id = student["id"]
total_score = sum(student.values())
if student_id not in students_scores:
students_scores[student_id] = {"total_score": total_score, "num_subjects": len(student)}
# 计算平均分
average_scores = {student_id: total_score / num_subjects for student_id, data in students_scores.items()}
print("每位同学所有科目的平均值:")
for student, avg_score in average_scores.items():
print(f"{student}: 平均分: {avg_score}")
阅读全文