列出索引超出范围,python故障排除


for i in range(0,len(text_list)):
    if (text_list[i] == "!" and text_list[i+1].isupper()):
        print "something"
    else:
        text_list.pop(i)

Traceback(最近一次通话):

  File "test.py", line 12, in <module>
    if (text_list[i]=="!" and text_list[i+1].isupper()):

错误:

IndexError: list index out of range

我想从文本文件中删除所有不在句子末尾的感叹号。

i变得len(text_list) - 1时,i + i是越界的。这是你的第一个问题。第二个问题是你在 for 循环中弹出。这将更改列表的大小。

我建议将要删除的索引保存在单独的列表中,然后在循环完成后弹出它们。

to_remove = []
for i in range(0,len(text_list) - 1):
    if (text_list[i]=="!" and text_list[i+1].isupper()):                
        print "something"   
    else:
        to_remove.append(i)
for i in reversed(to_remove):
    text_list.pop(i) # use del if you don't need the popped value

当你的 i 成为text_list的最后一个索引时,"text_list[i+1].isupper()" 会给你错误,因为 i+1 将超出索引范围。你可以做这样的事情:

for i in range(0,len(text_list)):
    if(i!=len(text_list-1)):
        if (text_list[i]=="!" and text_list[i+1].isupper()):                
            print "something"   
        else:
            text_list.pop(i)

最新更新