简体   繁体   English

列表索引超出范围

[英]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但是我得到了错误:列表索引超出范围

What's the problem here?这里有什么问题?

btw, besides "at +=1" , is there any other way to finish this cycle loop?顺便说一句,除了"at +=1"之外,还有其他方法可以完成这个循环吗? thx谢谢

The problem is that lines has a maximum value of len(input)-1 but then you let line4 be lines + 3 .问题是lines的最大值是len(input)-1但是你让line4lines + 3 So, when you're at your last couple of lines, lines + 3 will be larger than the length of the list.因此,当您在最后几行时, lines + 3将大于列表的长度。

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

Lets say len(input) == 10 .可以说len(input) == 10 range(0, len(input)) iterates [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] . range(0, len(input))迭代[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.当行 > 6 并且您尝试访问input[lines+3 ] 时,它显然是一个 IndexError,因为没有index[10][11]等。

And line1.split(':')[4] can also raise an IndexError if line1.count(":") < 4 .如果line1.count(":") < 4line1.split(':')[4]也可以引发 IndexError 。

I didn't understand the last at part, it seems not doing anything, but you can break the loop easily with break statement.我不明白最后一部分at它似乎什么也没做,但你可以用break语句轻松地打破循环。

Also, naming a variable input is a bad idea because it conflicts with builtin input function.此外,命名变量input是一个坏主意,因为它与内置input function 冲突。 And range(0, len(input)) == range(len(input)) , so 0 as range's first argument is unnecessary.range(0, len(input)) == range(len(input)) ,所以 0 作为 range 的第一个参数是不必要的。

I had a similar problem and here is the solution I came up with:我有一个类似的问题,这是我想出的解决方案:

tuple = (1,2,3)

dogs = [ ]

cats = [ ]

one_two = [ ]

cats.apend(tuple)

dogs.apend(tuple)

file.apend(one_two)

file.apend("/")

print file
print cats
print dogs

Have an excellent day.有一个美好的一天。

It seems that you want to read a file and get some info from it every 3 lines.您似乎想每 3 行读取一个文件并从中获取一些信息。 I would recommend something simpler:我会推荐一些更简单的东西:

def get_num(line):
    return line.split(':')[4].split()[0]

nums1 = [get_num(l) for l in open(fn, "r").readlines()]
nums2 = nums1[3:]
for i in range(len(nums2)):
    print nums1[i],nums2[i]

The last 3 numbers of nums1 won't be written.不会写入 nums1 的最后 3 个数字。 The variable at does not do anything in your code.变量 at 不会在您的代码中执行任何操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM