Python按要求统计学生的课程成绩
时间: 2024-02-03 07:13:32 浏览: 23
假设有如下的学生成绩数据:
```
scores = [
{'name': 'Alice', 'math': 90, 'english': 85, 'history': 92},
{'name': 'Bob', 'math': 75, 'english': 80, 'history': 85},
{'name': 'Charlie', 'math': 65, 'english': 70, 'history': 75},
{'name': 'David', 'math': 80, 'english': 75, 'history': 70},
{'name': 'Eve', 'math': 95, 'english': 90, 'history': 85},
]
```
要求统计每个学生的总成绩、平均成绩,并计算每门课程的平均成绩。
可以按照以下步骤进行统计:
1. 遍历每个学生,累加每个学生的总成绩和每门课程的总成绩;
2. 计算每个学生的平均成绩和每门课程的平均成绩。
完整的 Python 代码如下:
```python
scores = [
{'name': 'Alice', 'math': 90, 'english': 85, 'history': 92},
{'name': 'Bob', 'math': 75, 'english': 80, 'history': 85},
{'name': 'Charlie', 'math': 65, 'english': 70, 'history': 75},
{'name': 'David', 'math': 80, 'english': 75, 'history': 70},
{'name': 'Eve', 'math': 95, 'english': 90, 'history': 85},
]
# 初始化每门课程的总成绩和人数
math_total = 0
english_total = 0
history_total = 0
num_students = len(scores)
# 遍历每个学生,累加每个学生的总成绩和每门课程的总成绩
for student in scores:
math_total += student['math']
english_total += student['english']
history_total += student['history']
student['total'] = student['math'] + student['english'] + student['history']
student['average'] = student['total'] / 3
# 计算每门课程的平均成绩
math_avg = math_total / num_students
english_avg = english_total / num_students
history_avg = history_total / num_students
# 输出每个学生的成绩统计信息
for student in scores:
print('Name:', student['name'])
print('Total score:', student['total'])
print('Average score:', student['average'])
print()
# 输出每门课程的平均成绩
print('Math average:', math_avg)
print('English average:', english_avg)
print('History average:', history_avg)
```
输出结果如下:
```
Name: Alice
Total score: 267
Average score: 89.0
Name: Bob
Total score: 240
Average score: 80.0
Name: Charlie
Total score: 210
Average score: 70.0
Name: David
Total score: 225
Average score: 75.0
Name: Eve
Total score: 270
Average score: 90.0
Math average: 81.0
English average: 80.0
History average: 81.4
```