我必须计算python中某人的平均成绩。我收到了一个输入文件,并结合起来,我必须计算每个人的平均成绩。我做了很多尝试,但我的平均成绩仅为第一人称。.有人可以帮助我吗?
输入文件如下:
Tom Bombadil__________6.5 5.5 4.5
Dain IJzervoet________6.7 7.2 7.7
Thorin Eikenschild____6.8 7.8 7.3
Meriadoc Brandebok____1.0 5.0 7.7
Sam Gewissies_________2.3 4.5 6.7
输出如下:
Tom Bombadilhas an average grade of 5.5
Dain IJzervoethas an average grade of 5.5
Thorin Eikenschildhas an average grade of 5.5
Meriadoc Brandebokhas an average grade of 5.5
Sam Gewissieshas an average grade of 5.5
我使用以下代码:
def names(lines):
for i in lines:
invoer_split = i.split("_")
first_name = invoer_split[0]
print first_name + "has an average grade of %.1f" %(average_grade(names))
def average_grade(names):
for i in lines:
grades_split = i.split("_")
grades = grades_split[-1]
grades_float = map(float,grades.split())
grades_average = sum(grades_float)/3
return grades_average
grades_file = open('grades1+2.in')
lines = grades_file.readlines()
names(lines)
average_grade(names)
最佳答案
不必分开处理名称和等级,而是同时进行。我们将输入更改为字典,将字符串映射为浮点数。
with open('filename') as f:
grades_dict = {}
for line in f:
name, *underscores, grades = line.split('_') #I forget when this syntax became a thing. You might have to assign these separately
grades = list(map(float, grades.split()))
grades_dict[name] = sum(grades)/len(grades)
for name, grade in grades_dict.items():
print('{0} has an avergae grade of {1}'.format(name, grade))
关于python - 计算平均成绩不会成功,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40658662/