我正在尝试编写一个程序,我需要能够输入 4 个不同科目的 5 个学生分数,然后输出学生和科目的最高平均分。
所需的输入和输出是:
Student 1 (courses 1-4): 50 60 70 60
Student 2 (courses 1-4): 100 90 87 90
Student 3 (courses 1-4): 70 100 90 90
Student 4 (courses 1-4): 30 65 50 50
Student 5 (courses 1-4): 58 50 74 43
The highest average mark of students: 91.75
The highest average mark of courses: 74.2
我当前的代码适用于计算一门科目,而不是 4 门科目。我如何才能为每个学生输入 4 个成绩以获得我想要的输出。
请参阅下面的代码:
m1 = int(input("Student 1 (courses 1-4): "))
m2 = int(input("Student 2 (courses 1-4): "))
m3 = int(input("Student 3 (courses 1-4): "))
m4 = int(input("Student 4 (courses 1-4): "))
m5 = int(input("Student 5 (courses 1-4): "))
avg = (m1 + m2+ m3+ m4 + m5) / 5;
avg1 =(m1 + m2+ m3+ m4 + m5) / 20;
print("The Highest average mark of students =", avg)
print("The Highest average mark of courses =", avg1)
最佳答案
这段代码完成了这项工作,
import pandas as pd
import numpy as np
# Part 1
student_num = 5
all_marks = []
for i in range(student_num):
marks = input(f"Student {i + 1} (courses 1-4): ")
all_marks.append(list(map(float, marks.split(" "))))
# Part 2
df = pd.DataFrame(all_marks, columns = ['Marks'])
course_avg = df.Marks.apply(np.mean)
student_avg = df.Marks.apply(np.mean, axis = 1)
代码的第一部分将输入转换为数字并将它们存储到列表中。然后在第 2 部分中将该列表转换为数据框。我首先在列上应用 np.mean
来查找每门类(class)的平均值,然后在行上应用来查找每个学生的平均值。
您可以在 course_avg
和 student_avg
上使用 idxmax()
来查找最大平均值的索引,并找到具有以下值的类(class)/学生:相应地最高平均值。
(最好将值直接存储在 .xlsx 或 .csv 文件中,而不是通过这种方式通过 Python 输入。获得文件后,只需在 pd 中传递文件路径即可.read_excel()
或 pd.read_csv()
取决于文件的格式。)
关于python - 程序输入 4 个科目的 5 个学生分数,并输出学生和科目的最高平均分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72008244/