计算平均等级不会成功

时间:2016-11-17 15:21:25

标签: python list output

我必须计算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)

2 个答案:

答案 0 :(得分:1)

不要单独处理名称和成绩,而是同时进行。我们将输入更改为将字符串映射到float的字典。

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))

答案 1 :(得分:0)

作为Patrick解决方案的替代方案,您可以使用它。

def average_grade(grades_string):
    # split on whitespace
    grades = grades_string.split(' ')
    # convert to floats (we convert map to list for python3 compatibility)
    grades = list(map(float, grades))
    # return the average
    return sum(grades)/len(grades)

# This is the same as "lines = open()", but closes the file after we finish
with open('grades1+2.txt') as lines:
    # Start iterating
    for line in lines:
        # When we split by underscores, we will get three parts:
        # the name; the empty string (where underscores were); the grades.
        # We can do that in one assignment
        name, ignore_this, grades_str = line.split('_')
        # now print the result (converting average to string)
        print(name + ' has an average of ' + str(average_score(grades_str)))