-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:我不能使用任何內置列表方法。
'temp'是一個空列表。試試'temp.append(...)'或'temp = self..'它應該解決問題 – Nuageux
無法使用.append() –
您已經在使用內置方法。 '[]'是一種內置的方法。 – khelwood