[英]Exception error 'list index out of range.'
I have a text file (txt_file.txt).我有一个文本文件 (txt_file.txt)。 Data contain 26 lines as below.数据包含 26 行,如下所示。
AAA --> 1st line
BBB
CCC
...
ZZZ -->26th line
I have code for read each line.我有阅读每一行的代码。
with open('txt_file.txt') as file:
lines = [line.rstrip() for line in file]
#print(lines) # or lines[1]
subs = [((0, 3), lines[1] +'\n'+lines[2]),
((4, 7), lines[3] +'\n'+lines[4]),
((8, 11), lines[5] +'\n'+lines[6]),
((12, 15), lines[7] +'\n'+lines[8]),
((16, 19), lines[9] +'\n'+lines[10]),
((20, 23), lines[11] +'\n'+lines[12]),
((24, 27), lines[13] +'\n'+lines[14]),
((28, 31), lines[15] +'\n'+lines[16]),
((32, 35), lines[17] +'\n'+lines[18]),
((36, 39), lines[19] +'\n'+lines[20]),
((40, 43), lines[21] +'\n'+lines[22]),
((44, 47), lines[23] +'\n'+lines[24]),
((48, 51), lines[25] +'\n'+lines[26]),
((52, 55), lines[27] +'\n'+lines[28]),
((56, 59), lines[29] +'\n'+lines[30]),]
error 'list index out of range' occur.发生错误“列表索引超出范围”。
But I don't want to change subs =
because when I input (txt_file.txt) next time.但是我不想更改subs =
因为当我下次输入 (txt_file.txt) 时。 It maybe is contained more or less than 26 lines.它可能包含多于或少于 26 行。 I want to exception 'list index out of range' error.我想排除“列表索引超出范围”错误。
Since your numbers are following a linear rule, you can construct them programmatically instead of hardcoding them:由于您的数字遵循线性规则,因此您可以通过编程方式构造它们,而不是对它们进行硬编码:
subs = [((4 * i, 4 * i + 3), lines[l + 1] + '\n' + lines[l + 2])
for i, l in enumerate(range(0, len(lines) - 2, 2))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.