您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

您正在修改要遍历的列表。如果这样做,列表的大小将缩小,因此最终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]
python 2022/1/1 18:38:52 有381人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶