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

本文探讨了在Python中,当在for循环中尝试从列表中删除元素导致'IndexError: list index out of range'的问题。作者指出这是由于在迭代过程中修改列表大小,给出了修复方法——创建新列表过滤元素。
摘要由CSDN通过智能技术生成

1586010002-jmsa.png

for i in range(len(lst)):

if lst[i][0]==1 or lst[i][1]==1:

lst.remove(lst[i])

return lst

This gives "IndexError: list index out of range" Why is this happening?

解决方案

You're modifying the list you're iterating over. If you do that, the size of the list shrinks, so eventually lst[i] will point beyond the list's boundaries.

>>> lst = [1,2,3]

>>> lst[2]

3

>>> lst.remove(1)

>>> lst[1]

3

>>> lst[2]

Traceback (most recent call last):

File "", line 1, in

IndexError: list index out of range

It's safer to construct a new list:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值