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

2024-04-25 07:14:37 发布

您现在位置:Python中文网/ 问答频道 /正文

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

这就给出了“indexeror:list index out of range”为什么会发生这种情况?


Tags: orofinforindexlenreturnif
3条回答

你在修改你正在迭代的列表。如果这样做,列表的大小将缩小,因此最终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]

当您在list中迭代时,不应该remove项;这会更改所有后续项的索引,因此IndexError。你可以尝试一个简单的列表理解:

lst = [item for item in lst if (item[0] != 1 and item[1] != 1)]

一般来说,这意味着您提供的索引的列表元素不存在。

例如,如果您的列表是[12、32、50、71],并且您要求索引10处的元素,那么您将完全超出范围并收到错误,因为只有元素0到3存在。

相关问题 更多 >