MrF*_*HHH 2 python dictionary average
我试图找到全班数学平均分,但我不知道如何在字典中做到这一点。如何使用简单的方法将每个分数相加,然后除以学生人数 (num_students)?
login="teacher"
password="school"
usrnm=input("Please enter your username: ")
pw=input("Please enter your password: ")
if (usrnm==login) and (pw==password):
print("==Welcome to the Mathematics Score Entry Program==")
num_students = int(input("Please enter number of students:"))
print ("you entered ",num_students," students")
student_info = {}
student_data = ['Maths Score: ']
for i in range(0,num_students):
student_name = input("Name :")
student_info[student_name] = {}
for entry in student_data:
student_info[student_name][entry] = int(input(entry))
print (student_info)
else:
print("No way, Jose!")
Run Code Online (Sandbox Code Playgroud)
python 字典有一个.values()
方法,它返回您可以使用的字典中的值列表,例如:
sum(d.values()) / float(len(d))
Run Code Online (Sandbox Code Playgroud)
d.values()
给出你的学生的分数列表,sum(..)
给出所有分数的总和,我将其除以len(d)
字典的整数长度(即分数的数量),显然平均值是分数的总和/分数的数量。
你需要浮点数,因为 python 2 否则会返回一个整数(python 3 在适当的时候给出浮点数)