2016-01-22 50 views
0

我寫了這個功能:指數錯誤:列表分配索引超出範圍

def replace(self, pos, note): 
    """ 
     Replace the score of the participant at the given position with a new score 
     Input: pos, note - integer 
     Output: the old score was replaced 
    """ 


    scores = self.repo.getAll() 

    scores[pos] = note 
    return scores 

凡GETALL類participantRepo的定義如下:

def getAll(self): 
     return self._participantList[:]. 

我的問題是,我不明白錯誤我不斷收到

回答

0

如果列表中還沒有至少有pos+1個元素,list[pos]會嘗試將note指定給外部索引 列表。您可以使用append()方法將項目添加到列表中。

0

如果此代碼

scores[pos] = note 

導致此錯誤:

Index error: list assignment index out of range 

你可以把它解釋是這樣的:

  1. 列表分配索引指的是「分數[POS ] ='。 的POS'是索引; '分數'是列表名稱。 您將值「注意」到列表索引。
  2. 超出範圍指示正被用於的POS'的數目不爲列表的分數「爲當前指定的一個有效的索引。

一種方式進行調試:

列表分配之前添加打印語句,向您展示的POS'的值。如果您知道列表索引的有效範圍,則可以幫助您追蹤發生此錯誤的位置和原因。

0

您的代碼應處理out of bound access如下

def replace(self, pos, note): 
""" 
Replace the score of the participant at the given position with a new score 
Input: pos, note - integer 
Output: the old score was replaced 
""" 
    scores = self.repo.getAll() 

    if pos < len(scores): 
     scores[pos] = note 
    else: throw IndexError 
    return scores 

`

相關問題