【问题标题】:getting an error while executing the code执行代码时出错
【发布时间】:2013-03-13 05:43:05
【问题描述】:

在下面的代码中,我想打印“first”之间的行,以及在那些搜索“new.txt”行的行上。当我运行时出现错误:

if "first" in lines[i+n]:
IndexError: list index out of range

我的代码:

def find_path(self):
        f = open("/output",'w')
        for line in self.logs:
            f.write(line)
        f = open('/output','rb')
        lines = f.readlines()
        for i,line in enumerate(lines):    
            if "first" in line:
                pattern = line
                for n in range(1,len(lines)):
                    if "first" in lines[i+n]:
                        break
                    else: 
                        if "new.txt" in line:
                            print line
                        print lines[i+n]
        f.close()               

【问题讨论】:

    标签: python python-2.6


    【解决方案1】:

    这是因为i+n 可以并且将大于lines 列表的长度。

    for i,line in enumerate(lines):    
    

    该枚举为i 创建从0len(lines) - 1 的值,因此i 的最大值为len(lines) - 1

    以下几行告诉我们n 的值可以从1len(lines) - 1,所以n 的最大值又是len(lines) - 1

    for n in range(1,len(lines)):
        if "first" in lines[i+n]:
            break  
    

    所以,i + n 的值可以从 12 * (len(lines) - 1) - 这就是你得到 IndexError 的原因。

    【讨论】:

    • 如何解决?...我尝试使用 len(lines)-1 但仍然出现错误
    • 我不明白你的代码的意思,如果你能解释一下,也许我会找到帮助你解决问题的方法。
    猜你喜欢
    • 1970-01-01
    • 2017-03-15
    • 1970-01-01
    • 2018-03-18
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多