我正在嘗試撰寫一個程式,我需要能夠在 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)
uj5u.com熱心網友回復:
這段代碼完成了這項作業,
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
marks = pd.DataFrame(all_marks)
course_avg = marks.apply(np.mean)
student_avg = marks.apply(np.mean, axis = 1)
代碼的第一部分將輸入轉換為數字,然后存盤在一個串列中。然后在第 2 部分中將此串列轉換為資料框。我首先np.mean在列上應用以找到每門課程的平均數,然后在行上應用以找到每個學生的平均數。
您可以idxmax()同時使用course_avg和student_avg來查找最大平均數的索引,并相應地找到平均數最高的課程/學生。
(最好將值直接存盤在 .xlsx 或 .csv 檔案中,而不是通過 Python 以這種方式輸入它們。一旦有了檔案,只需將檔案路徑傳入pd.read_excel()或pd.read_csv()根據檔案的格式傳遞。)
uj5u.com熱心網友回復:
首先,創建一個字典來輸入每個學生的分數。讓我們稱之為d_marks。創建一個字典來獲取所有學生的平均值。讓我們稱之為avg_marks。創建字典以獲取所有課程的總分。讓我們稱之為avg_course。之后得到max他們。以下是您的操作方法:
d_marks = {}
avg_marks = {}
avg_course = {}
for i in range(1,6): # We loop for 5 students
d_marks[f'Student {i} (courses 1-4)'] = list(map(int, input(f"Student {i} (courses 1-4): ").split())) # Split the string and creates an integer list
avg_marks[f'Average of Student {i}'] = sum(d_marks[f'Student {i} (courses 1-4)']) / len(d_marks[f'Student {i} (courses 1-4)']) #Create average dictionary for Students
for j in range(1, len(d_marks[f'Student {i} (courses 1-4)']) 1):
if f'Course {j} sum' in avg_course: # if course sum already in dictionary then add it to previous.
avg_course[f'Course {j} sum'] = d_marks[f'Student {i} (courses 1-4)'][j-1]
else:
avg_course[f'Course {j} sum'] = d_marks[f'Student {i} (courses 1-4)'][j-1] # if course sum not in dictionary then create one.
print("The Highest average mark of students =", max(avg_marks.values()))
print("The Highest average mark of courses =", max(avg_course.values())/ len(d_marks))
輸出:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/464518.html
標籤:Python python-3.x
上一篇:我該如何做到這一點,以便線條繼續顯示新字母而不是擺脫已經顯示的字母?
下一篇:Python:如何替換大量字串
