Firstly, input an integer � N, which represents a total of � N students. Then enter � N lines, each containing the student's name, class, exam 1 score, and exam 2 score. Count the average and total scores of each exam for each class, and sort the results by class name before outputting them to the console. Output includes class, score1_mean, score1_sum, score2_mean, score2_sum.
时间: 2024-02-01 11:03:19 浏览: 46
The GOAL- By Evan.pptx
以下是使用pandas解决该问题的代码实现:
``` python
import pandas as pd
# 读取学生信息
n = int(input())
data = []
for i in range(n):
line = input().split()
data.append(line)
# 创建DataFrame
df = pd.DataFrame(data, columns=['name', 'class', 'exam1', 'exam2'])
df[['exam1', 'exam2']] = df[['exam1', 'exam2']].astype(float)
# 计算各班级的平均分和总分
result = df.groupby('class').agg({'exam1': ['mean', 'sum'], 'exam2': ['mean', 'sum']})
# 对结果按班级名称排序
result = result.sort_values(by='class')
# 输出结果
print(result.to_string(header=['score1_mean', 'score1_sum', 'score2_mean', 'score2_sum'], \
formatters={'score1_mean': '{:.2f}'.format, 'score1_sum': '{:.2f}'.format, \
'score2_mean': '{:.2f}'.format, 'score2_sum': '{:.2f}'.format}))
```
上述代码与前面的代码实现基本相同,但是在最后输出结果时使用了to_string函数,并指定header和formatters参数,以便将结果输出为指定格式。同时对结果按班级名称进行了排序。最终输出结果。
阅读全文