簡體   English   中英

Python - 僅在循環內運行/執行 IF 語句一次

[英]Python - run/execute IF statement only once inside loop

如何只在另一個 IF 中執行/運行 IF 語句一次? 我正在逐行讀取文件,我只想在 IF 語句中執行一次命令。

我嘗試過全局變量,定義並調用 Function,但沒有運氣。

請你幫助我好嗎?

例子:

  i = 0 
  for x in enumerate(FILE, 1):
    i += 1
    
    if re.findall("*test1*", line):
      
      command1
      command2
      command3
      
      executed = True; (...and do not run commands again when the IF statement is fullfiled with another line from FILE)


 

只需向 if 語句添加迭代要求,如下所示:

i = 0 
j=0
for x in enumerate(FILE, 1):
    i += 1
    
    if j == 0 and re.findall("*test1*", line):
        j+=1
        command1
        command2
        command3

這意味着它只會在第一次執行時起作用。

如果您願意,可以改為使用“已執行”變量:

i = 0 
executed = False
for x in enumerate(FILE, 1):
    i += 1
    
    if executed == False and re.findall("*test1*", line):
        command1
        command2
        command3
        executed = True

最后,如果你想在第一次執行后完全退出循環,你可以像這樣使用break

i = 0 
for x in enumerate(FILE, 1):
    i += 1
    
    if re.findall("*test1*", line):
        command1
        command2
        command3
        break

取決於您是否需要繼續循環。

您可以做的是在運行測試之前測試not executed ,然后如果executedtrue ,則不會運行正則表達式。
例子:

  executed = False
  i = 0 
  for x in enumerate(FILE, 1):
    i += 1
    
    if ((not executed) and re.findall("*test1*", line)):
      # ... commands
      executed = True; 
      #don't run commands again when the IF statement sees executed is True

如果您只想忽略它們,另一種選擇是跳過這些行的 rest。 例子:

  i = 0 
  for x in enumerate(FILE, 1):
    i += 1
    if (re.findall("*test1*", line)):
      # ... commands
      executed = True
      break # the break will exit the for loop

如果這不能回答您的問題,請在評論中告訴我。 因為它似乎符合您對問題的描述,並且有效。

暫無
暫無

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

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