本文介绍了IndexError:超出python的字符串列表索引范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从此数组中删除单词"hello",但出现索引超出范围"错误.我检查了len(token)的范围;是(0,5).

I wanted to remove the word "hello" from this array, but I get the "index out of bounds" error. I checked the range of len(token); it was (0,5).

这是代码:

token=['hi','hello','how','are','you']

stop='hello'

for i in range(len(token)):
    if(token[i]==stop):
        del(token[i])

推荐答案

您正在获取索引超出范围的异常,因为要从要迭代的数组中删除一项.

You're getting an index out of bounds exception because you are deleting an item from an array you're iterating over.

删除该项目后,len(token)为4,但是您的for循环正在重复5次(从初始len(token)返回5次).

After you delete that item, len(token) is 4, but your for loop is iterating 5 times (5 being returned from the initial len(token)).

有两种方法可以解决此问题.更好的方法是简单地调用

There are two ways to solve this. The better way would be to simply call

token.remove(stop)

这种方法不需要遍历列表,并且会自动删除值stop的数组中的第一项.

This way won't require iterating over the list, and will automatically remove the first item in the array with the value of stop.

文档:

鉴于此信息,您可能需要检查列表中是否首先包含目标元素,以避免引发ValueError:

Given this information, you may want to check if the list contains the target element first to avoid throwing a ValueError:

if stop in token:
    token.remove(stop)

如果该元素可以在列表中多次存在,则使用while循环将删除该元素的所有实例:

If the element can exist multiple times in the list, utilizing a while loop will remove all instances of it:

while stop in token:
    token.remove(stop)

如果由于某种原因需要遍历数组,另一种方法是在del(token[i])之后添加break,如下所示:

If you need to iterate over the array for some reason, the other way would be to add a break after del(token[i]), like this:

for i in range(len(token)):
    if(token[i]==stop):
        del(token[i])
        break

这篇关于IndexError:超出python的字符串列表索引范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 02:39