我想从该数组中删除“hello”一词,但出现“索引越界”错误。我检查了 len(token)
的范围;这是(0,5)
.
这是代码:
token=['hi','hello','how','are','you']
stop='hello'
for i in range(len(token)):
if(token[i]==stop):
del(token[i])
最佳答案
您收到索引越界异常,因为您正在从正在迭代的数组中删除一个项目。
删除该项目后,len(token)
为 4,但您的 for
循环迭代了 5 次(5 从初始 len( token )
)。
有两种方法可以解决这个问题。更好的方法是简单地调用
token.remove(stop)
这种方式不需要迭代列表,并且会自动删除数组中值为 stop
的第一项。
来自documentation :
list.remove(x)
: Remove the first item from the list whose value is x. It is an error if there is no such item.
鉴于此信息,您可能需要首先检查列表是否包含目标元素以避免抛出 ValueError
:
if stop in token:
token.remove(stop)
如果该元素可以在列表中多次存在,则使用 while
循环将删除它的所有实例:
while stop in token:
token.remove(stop)
如果出于某种原因需要迭代数组,另一种方法是在 del(token[i])
之后添加 break
,如下所示:
for i in range(len(token)):
if(token[i]==stop):
del(token[i])
break
关于python - 索引错误: list index out of range in python for strings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35517360/