简体   繁体   English

Python字典中的平均值

[英]Average in Dictionary in Python

I am trying to find the average of maths score for the class but I am not sure how to do this within a dictionary. 我正在尝试查找班级的数学平均分数,但是我不确定如何在字典中做到这一点。 How do I use a simple method of adding each score then dividing this by the number of students (num_students)? 如何使用简单的方法将每个分数相加然后除以学生人数(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!")

Calculating the average can be done using the sum function as follows: 可以使用sum函数来计算平均值,如下所示:

average = sum(d['Maths Score: '] for d in student_info.values()) / len(student_info)

Note that currently your code can only have students with unique names. 请注意,当前您的代码只能有具有唯一名称的学生。 Two students with the same name will override each other. 具有相同名称的两个学生将互相覆盖。

python dictionaries have a .values() method which returns a list of the values in a dictionary which you can use, eg: python字典有一个.values()方法,该方法返回您可以使用的字典中的值列表,例如:

sum(d.values()) / float(len(d))

d.values() give the list of marks for your students, sum(..) gives the total of all the marks, which I divide by len(d) which is the integer length of the dictionary (ie the number of marks) obviously average is total of marks / number of marks. d.values()给出学生的分数列表, sum(..)给出所有分数的总和,我将其除以len(d) ,即字典的整数长度(即分数的数量)显然,平均数是总分数/分数。

you need the float because python 2 will return an integer otherwise (python 3 gives floats when appropriate) 您需要float,因为python 2否则将返回一个整数(python 3在适当的时候给出float)

If you're using Python 3.4+, then you can use statistics.mean : 如果您使用的是Python 3.4+,则可以使用statistics.mean

from statistics import mean
avg_score = mean(d.values())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM