首页 > 解决方案 > 为什么我的 for 循环只在第一项上执行?

问题描述

我有一个要与文件匹配的正则表达式列表,以及匹配发生的行号以添加到特定于该正则表达式的列表中。

regexes = [r"Repl ex\s+0\s+x\s+1", r"Repl ex.*1\s+x\s+2", r"Repl ex.*2\s+x\s+3",
           r"Repl ex.*3\s+x\s+4", r"Repl ex.*4\s+x\s+5", r"Repl ex.*5\s+x\s+6",
           r"Repl ex.*6\s+x\s+7", r"Repl ex.*7\s+x\s+8", r"Repl ex.*8\s+x\s+9",
           r"Repl ex.*9\s+x\s+10", r"Repl ex.*10\s+x\s+11", r"Repl ex.*11\s+x\s+12",
           r"Repl ex.*12\s+x\s+13", r"Repl ex.*13\s+x\s+14", r"Repl ex.*14\s+x\s+15",
           r"Repl ex.*15\s+x\s+16", r"Repl ex.*16\s+x\s+17", r"Repl ex.*17\s+x\s+18",
           r"Repl ex.*18\s+x\s+19"]


exchanges = [[] for i in range(19)]
# open the md.log file
f = open('myfile', 'r')


for x in range(19):
    for i, line in enumerate(f):
        if re.compile(regexes[x]).match(line):
            exchanges[x].append(i)

上面的代码给出了 exchange[0] 的预期结果,但之后返回以下 17 个项目的空列表。如果我用“1”代替“x”运行它,我会得到下一个正则表达式的正确结果,所以我知道正则表达式是匹配的。

标签: python

解决方案


您正在尝试使用相同的文件描述符一遍又一遍地迭代同一个文件。每当您读取一行时,描述符都会指向文件中的下一个。在第一次迭代中,文件将被完全读取,并且描述符将不再有要读取的行,这就是为什么您的内部循环不会多次执行的原因。要解决此问题,请将文件内容存储在列表中并对其进行迭代。

exchanges = [[] for i in range(19)]
# open the md.log file
f = open('myfile', 'r')
contents = f.readlines()
f.close()

for x in range(19):
    for i, line in enumerate(contents):
        if re.compile(regexes[x]).match(line):
            exchanges[x].append(i)

推荐阅读