簡體   English   中英

如何通過2次迭代來推進for循環?

[英]How to advance a for loop by 2 iterations?

我正在讀取一個大型文本文件,並且需要從特定行讀取一個數字。 該文件如下所示:

....
unknown number of lines
....
ABCD
some random stuff
a number I want to read
....
....

我想從ABCD的“簽名”行之后的2行開始讀取數字,這是唯一的。 現在我正在做的是:

with open(filename,'r') as f:
  for line in f:
    if line.rstrip('\n') == 'ABCD':
      continue

但是continue只將for循環前進1次迭代。 因此,如何使它又進行一次迭代以獲得我實際需要的行?

您可以在f *上顯式調用next (for循環通常為您執行此操作),並推進迭代器,然后調用continue

for line in f:
    if line.rstrip('\n') == 'ABCD':
        next(f)
        continue
    print(line)

現在將打印:

....

unknown number of lines

....

a number I want to read

....

....

從而跳過'ABCD''some random stuff'

在通常情況下,您確定ABCD 不是最終要素,這應該不會引起問題。 但是,如果您出於安全考慮,可以try - except將其包裝try - except捕獲StopIteration異常之外。


*在這種情況下,這是iter(f) is f ,因為f是它自己的iteratoriter(f) is f 通常,情況並非如此,對於列表來說,迭代器是它自己的獨立對象list_iterator因此像這樣推進它是行不通的。

如果您要堅持這種方法,請執行以下操作:

f = open(filename,'r'):
while f.readline().rstrip('\n') != 'ABCD': # this will advanced the pointer to the ABCD line
    continue
f.next() # to skip over the unnecessary stuff
desiredNumber = f.readline()  # desired line

我認為regex看起來會好很多,但是如果您想要完成某項工作,就可以了。

如果您根本不需要跳過的行中的任何信息,則可以在continue操作之前手動將文件前進一行。

with open(filename,'r') as f:
    for line in f:
        if line.rstrip('\n') == 'ABCD':
            next(f)     # The next iteration of the for loop will skip a line
            continue

如果您需要此文件中的那一行,就根本不需要continue 只是跳行,搶下一行,做任何你需要用它做,並且break了的for循環,所有這一切中if塊。

我更喜歡@Jim使用next() ,但是另一個選擇是只使用一個標志:

with open(filename,'r') as f:
  skip_line = False
  for line in f:
    if line.rstrip('\n') == 'ABCD':
      skip_line = True
      continue
  if skip_line == True:
    skip_line = False
  else:
    print(line)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM