2012-11-09 18 views
-2

每一行代表一名學生,由學生人數,姓名,分段代碼和中期成績組成,全部由空白分隔。 第一個參數已經完成,該文件是開放的,
第二個參數是一款代碼 這是鏈接http://www.cdf.toronto.edu/~csc108h/fall/exercises/e3/grade_file.txt返回各自講座中的平均分數

我的代碼:

def average_by_section(the_file, section_code): 
    '''(io.TextIOWrapper, str) -> float 
    Return the average midtermmark for all students in that section 
    ''' 
     score = 0 
     n = 0 
     for element in the_file: 
      line = element.split() 
      if section_code == line[-2]: 
       mark = mark + float(line[-1]) 
       n += 1 

     lecture_avg = mark/n 
     return lecture_avg 

我發現了一個指數出來的範圍。它是否正確?或者我只是打開錯誤的文件?
有人可以測試此代碼並下載該文件?我很確定它應該工作,但不適合我。

+1

'score'應該是'mark'(反之亦然)? – RocketDonkey

回答

0

那麼,您可以使用print lineprint(line)來排除索引超出範圍錯誤,以探索「行」中的項目數(即split()的影響)。我建議在看你split()陳述更接近......

0

看起來你會忽略在其中定義了一些這些變量(section_codemark等)的代碼的部分,但在調整了一些這些東西似乎正常工作。假設您得到的錯誤是IndexError: list index out of range,那麼當您嘗試通過索引訪問列表中的某個元素(該索引不存在)時會發生這種情況。例如:

>>> l = ['one'] 
>>> l[0] 
'one' 
>>> l[1] 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
IndexError: list index out of range 
>>> l[-1] 
'one' 
>>> l[-2] 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
IndexError: list index out of range 

因此,在你的代碼,你會得到錯誤,如果line是有史以來少於兩個項目。我會檢查並看看你實際得到的line,以確保它是你所期望的。