python - 程序输入 4 个科目的 5 个学生分数,并输出学生和科目的最高平均分

标签 python python-3.x

我正在尝试编写一个程序,我需要能够输入 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_avgstudent_avg 上使用 idxmax() 来查找最大平均值的索引,并找到具有以下值的类(class)/学生:相应地最高平均值。

(最好将值直接存储在 .xlsx 或 .csv 文件中,而不是通过这种方式通过 Python 输入。获得文件后,只需在 pd 中传递文件路径即可.read_excel()pd.read_csv() 取决于文件的格式。)

关于python - 程序输入 4 个科目的 5 个学生分数,并输出学生和科目的最高平均分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72008244/

相关文章:

python - 重命名堆叠列

python - 通过glUnproject从鼠标坐标到世界坐标

python-3.x - 如何模拟第三方静态方法

python - 为什么在向字典中添加键时会出现 KeyError?

python-3.x - 如何选择 Pandas 中每个唯一记录的最后 5 行

python - 为什么 Python 3 允许 "00"作为 0 的文字,但不允许 "01"作为 1 的文字?

python - Python中随机种子的范围是什么?

python - Windows 上的 GeoDjango : "Could not find the GDAL library"/ "OSError: [WinError 126] The specified module could not be found"

python - mp3串流的python-proxy问题

python - 如何使用 Python 3.4.2 在 Windows 7 中安装 scipy