如何只在另一個 IF 中執行/運行 IF 陳述句一次?我正在逐行讀取檔案,我只想在 IF 陳述句中執行一次命令。
我曾嘗試過全域變數、定義和呼叫函式,但沒有運氣。
請你幫助我好嗎?
例子:
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)
uj5u.com熱心網友回復:
只需向 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
取決于您是否需要繼續回圈。
uj5u.com熱心網友回復:
您可以做的是not executed在運行測驗之前進行測驗,然后如果executed是true,則不會運行正則運算式。
例子 :
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
如果您只想忽略它們,另一種選擇是跳過其余的行。例子 :
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
如果這不能回答您的問題,請在評論中告訴我。因為它似乎符合您對問題的描述,并且有效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/420395.html
標籤:
