-2

以下のコードでは、「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()               
4

1 に答える 1

0

これは、リスト i+nの長さよりも長くなる可能性があるためです。lines

for i,line in enumerate(lines):    

その列挙は ~ ~ の値を作成するためi、の最大値はです。0len(lines) - 1ilen(lines) - 1

次の行は、 の値が~にnなる可能性があることを示しているため、 の最大値は再び になります。1len(lines) - 1nlen(lines) - 1

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

したがって、 の値はからまでにi + nなる可能性があります。そのため、 を取得しています。12 * (len(lines) - 1)IndexError

于 2013-03-13T05:46:03.510 に答える