列表索引超出范围 [英] list index out of range
问题描述
#!/usr/bin/python
import os,sys
from os import path
input = open('/home/XXXXXX/ERR001268_1', 'r').read().split('\n')
at = 1
for lines in range(0, len(input)):
line1 = input[lines]
line4 = input[lines+3]
num1 = line1.split(':')[4].split()[0]
num4 = line4.split(':')[4].split()[0]
print num1,num4
at += 1
但是我得到了错误:列表索引超出范围
However I got the error: list index out of range
这是什么问题?
btw,除了"at +=1"
之外,还有其他方法可以完成此循环吗?
btw, besides "at +=1"
, is there any other way to finish this cycle loop?
thx
推荐答案
让我们说len(input) == 10
. range(0, len(input))
迭代[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
.当行数> 6并且您尝试访问input[lines+3
]时,它显然是IndexError,因为没有index[10]
,[11]
等.
Lets say len(input) == 10
. range(0, len(input))
iterates [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
. And when lines > 6 and you're trying to access input[lines+3
], it clearly an IndexError, because there is no index[10]
, [11]
etc .
如果line1.count(":") < 4
,line1.split(':')[4]
也会引发IndexError.
And line1.split(':')[4]
can also raise an IndexError if line1.count(":") < 4
.
我不了解最后一个at
部分,似乎什么也没做,但是您可以使用break
语句轻松中断循环.
I didn't understand the last at
part, it seems not doing anything, but you can break the loop easily with break
statement.
此外,命名变量input
是一个坏主意,因为它与内置的input
函数冲突.而且range(0, len(input)) == range(len(input))
,因此不需要使用0作为范围的第一个参数.
Also, naming a variable input
is a bad idea because it conflicts with builtin input
function. And range(0, len(input)) == range(len(input))
, so 0 as range's first argument is unnecessary.
这篇关于列表索引超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!