(Python)列表索引超出范围 – 迭代

参见英文答案 > python : list index out of range error                                    9个
>            How to remove items from a list while iterating?                                    26个

for i in range(len(lst)):    
   if lst[i][0]==1 or lst[i][1]==1:
        lst.remove(lst[i])
return lst

这给出了“IndexError:list index超出范围”为什么会发生这种情况?

解决方法:

你正在修改你正在迭代的列表.如果你这样做,列表的大小会缩小,所以最终lst [i]将指向列表的边界之外.

>>> lst = [1,2,3]
>>> lst[2]
3
>>> lst.remove(1)
>>> lst[1]
3
>>> lst[2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

构建新列表更安全:

return [item for item in lst if item[0]!=1 and item[1]!=1]
上一篇:c – 找到最小的下一个更大的元素


下一篇:python – 有没有办法按索引合并多个列表索引?