在Python for循环中更新迭代值
我刚开始学Python,正在写一个脚本来从一个简单的日志文件中挑选特定的行。
这个功能的主要作用是搜索文件中的行,当找到我想要的那一行时,就把它输出到一个单独的文件里,并把它放进一个列表中。接着,它还会把后面五行也加进去。最后,这些内容会在另一个功能中输出到一个不同的文件。
我现在想做的是,在处理完那五行后,跳过它们,继续从最后一行开始,而不是再处理一遍。我以为代码的最后一行可以解决这个问题,但结果并没有。
有没有什么推荐的for循环的变体可以用来实现这个目的呢?
def readSingleDayLogs(aDir):
print 'Processing files in ' + str(aDir) + '\n'
lineNumber = 0
try:
open_aDirFile = open(aDir) #open the log file
for aLine in open_aDirFile: #total the num. lines in file
lineNumber = lineNumber + 1
lowerBound = 0
for lineIDX in range(lowerBound, lineNumber):
currentLine = linecache.getline(aDir, lineIDX)
if (bunch of logic conditions):
issueList.append(currentLine)
for extraLineIDX in range(1, 6): #loop over the next five lines of the error and append to issue list
extraLine = linecache.getline(aDir, lineIDX+ extraLineIDX) #get the x extra line after problem line
issueList.append(extraLine)
issueList.append('\n\n')
lowerBound = lineIDX
3 个回答
0
我会看看这样的东西:
from itertools import islice
with open('somefile') as fin:
line_count = 0
my_lines = []
for line in fin:
line_count += 1
if some_logic(line):
my_lines.append(line)
next_5 = list(islice(fin, 5))
line_count += len(next_5)
my_lines.extend(next_5)
这样一来,通过在输入上使用 islice
,你就可以把迭代器向前移动,并在消耗完5行(如果文件快结束,可能会少于5行)后继续。
这是基于我理解的,如果你可以向前读取文件,找到一行,然后只想要那行之后固定数量的行,然后再正常循环下去。(如果你只想要这些行,可能根本不需要计数,因为这似乎只是为了 getline
而已,没有其他用途)。
如果你确实想要接下来的5行,并且还想考虑下一行,你可以使用 itertools.tee
在出错的那一行分支,然后用 islice
来处理,让 fin
迭代器在下一行继续。
1
for循环是通过一个迭代器来遍历范围的,这样你就可以改变循环变量的值。
可以考虑使用while循环。这样的话,你就可以直接更新行索引。
3
你应该使用一个 while
循环:
line = lowerBound
while line < lineNumber:
...
if conditions:
...
for lineIDX in range(line, line+6):
...
line = line + 6
else:
line = line + 1