【问题标题】:Update iteration value in Python for loop在 Python for 循环中更新迭代值
【发布时间】:2013-01-30 01:27:06
【问题描述】:

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

【问题讨论】:

    标签: python for-loop


    【解决方案1】:

    您应该使用while 循环:

    line = lowerBound
    while line < lineNumber:
        ...
        if conditions:
            ...
            for lineIDX in range(line, line+6):
               ...
            line = line + 6
        else:
            line = line + 1
    

    【讨论】:

      【解决方案2】:

      for 循环在范围内使用迭代器,因此您可以更改循环变量。

      考虑改用 while 循环。这样,您可以直接更新行索引。

      【讨论】:

      • 是的,我现在用 while 重写了它,更容易操作。问题解决了谢谢。
      【解决方案3】:

      我会看类似的东西:

      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 行(如果接近文件末尾可能更少)耗尽后恢复。

      这是基于如果我理解正确,您可以向前读取文件,识别一行,并且只需要在该点之后固定数量的行,然后按正常方式恢复循环。 (如果这就是你所追求的,你甚至可能不需要计算行数,因为它似乎只用于getline 而不是任何其他目的)。

      如果你确实想要接下来的 5 个,并且仍然考虑下面的行,你可以使用 itertools.tee 在错误行的点进行分支,然后使用 islice 并让 fin 迭代器恢复在下一行。

      【讨论】:

        猜你喜欢
        • 2021-10-08
        • 2012-06-27
        • 2023-03-05
        • 1970-01-01
        • 2015-03-14
        • 2016-01-18
        • 2016-08-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多