2017-04-27 60 views
-2

我試圖從列表中刪除元素,但似乎在temp [index2]中出現「列表分配索引超出範圍」的錯誤分配線。以下是我的代碼。從列表中刪除元素時出現錯誤「索引超出範圍」

def remove(self, target_item): 
    if self.count == 0: 
     print("list is empty") 
    else: 
     index1 = 0 
     index2 = 0 
     temp = [] 
     while index1 < self.count: 
      if self.str_list[index1] != target_item: 
       temp[index2] = self.str_list[index1] 
      else: 
       self.count -= 1 
     index = 0 
     while index < self.count: 
      self.str_list[index] = temp.index 

有人可以解釋爲什麼我得到這個錯誤,我該如何解決這個問題?

PS:我不能使用任何內置列表方法。

+0

'temp'是一個空列表。試試'temp.append(...)'或'temp = self..'它應該解決問題 – Nuageux

+0

無法使用.append() –

+0

您已經在使用內置方法。 '[]'是一種內置的方法。 – khelwood

回答

1

你爲什麼試圖修改self.str_list inplace?只需構建一個新的過濾列表:

def remove(self, target_item): 
    self.str_list = [item for item in self.str_list if item != target_item] 
0

您的temp列表被初始化爲空。解決此問題的一種方法是將條件添加到if語句或初始化非空列表。

if len(temp) > 0 and self.str_list[index1] != target_item: 
    temp[index2] = self.str_list[index1] 
相關問題