2016-11-17 61 views
1

我必須計算某人在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) 
+0

請不要破壞你的帖子。 – ChrisF

回答

1

代替處理名和等級分開做,同時做。我們將把輸入變成一個將字符串映射到浮點的字典。

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

哇,這對我來說看起來很複雜..是不是有可能在我自己的代碼中做一點改動? – Max

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