辛苦一下各位大佬,看一下下面的代码。。。(第一次写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以下的就可以。辛苦各位大佬了。