Python 获取错误“;“索引超出范围”;从列表中删除元素时
我试图从列表中删除一个元素,但不知何故,在temp[index2]赋值行中似乎出现了“列表赋值索引超出范围”的错误。下面是我的代码Python 获取错误“;“索引超出范围”;从列表中删除元素时,python,list,function,Python,List,Function,我试图从列表中删除一个元素,但不知何故,在temp[index2]赋值行中似乎出现了“列表赋值索引超出范围”的错误。下面是我的代码 def remove(self, target_item): if self.count == 0: print("list is empty") else: index1 = 0 index2 = 0 temp = [] while index1 < self
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
def移除(自身、目标项目):
如果self.count==0:
打印(“列表为空”)
其他:
index1=0
index2=0
温度=[]
当index1
有人能解释一下我为什么会犯这个错误,以及我如何纠正这个错误吗
PS:我不能使用任何内置的列表方法。为什么您要在原地修改
self.stru list
?只需构建一个新的筛选列表:
def remove(self, target_item):
self.str_list = [item for item in self.str_list if item != target_item]
您的
temp
列表初始化为空。解决此问题的一种方法是向if
语句添加条件或初始化非空列表
if len(temp) > 0 and self.str_list[index1] != target_item:
temp[index2] = self.str_list[index1]
temp
是一个空列表。尝试temp.append(…)
或temp=self.
它应该可以解决您已经在使用内置方法的问题[]
是一种内置方法。temp
是一个空列表,进入循环时,index2=0
。您不能获取空列表的0
th索引。