IndexError: list index out of range

辛苦一下各位大佬,看一下下面的代码。。。(第一次写CSDN,格式不清楚,见谅!!)
代码如下:

test = [0, 0, 0, 0, 0, 2, 2, 3, 2, 1, 6, 7, 1]
global i
i = 0
print('test=', test, '\nlenth=', len(test))
for a in range(0, len(test)-1):
    if test[a] == 0 or test[a] == 1 or test[a] == 3:
        i = i + 1
    else:
        del test[a-1]
print('i= ', i, '\ntest= ', test) 

运行如上代码提示:

test= [0, 0, 0, 0, 0, 2, 2, 3, 2, 1, 6, 7, 1] 
lenth= 13
Traceback (most recent call last):
  File "D:/DP/PycharmProject/Project/test.py", line 6, in <module>
    if test[a] == 0 or test[a] == 1 or test[a] == 3:
IndexError: list index out of range

代码里面的“len(test)-1”很奇怪这个数要是设置成比某个数小,这个程序就可以运行。比如说<=10 的都是可以的。代码如下:

test = [0, 0, 0, 0, 0, 2, 2, 3, 2, 1, 6, 7, 1]
global i
i = 0
print('test=', test, '\nlenth=', len(test))
for a in range(0, 10):
    if test[a] == 0 or test[a] == 1 or test[a] == 3:
        i = i + 1
    else:
        del test[a-1]
print('i= ', i, '\ntest= ', test)

运行结果如下:

test= [0, 0, 0, 0, 0, 2, 2, 3, 2, 1, 6, 7, 1] 
lenth= 13
i=  7 
test=  [0, 0, 0, 0, 2, 2, 2, 6, 7, 1]

Process finished with exit code 0

上面的test[12]明明没有超出范围,可是这里为什么会提示出错呢?再弱弱的问一句,为什么10以上的数都不可以,而10以下的就可以。辛苦各位大佬了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值