我有一段代碼。在這里,我正在運行一個for回圈。如果if不滿足該陳述句,我想重新啟動該for回圈。我該怎么做?sp順便說一句,是一個圖書館。
for i in range (10000):
#my codes
a= sp.levene(#my variables)
if a[1] < 0.05:
#I want to restart for loop again
else:
#doing something
uj5u.com熱心網友回復:
您可能不想使用for回圈,因為您沒有迭代特定的數字序列(i將根據回圈內發生的情況進行跳轉)。使用while你會做的:
i = 0:
while i < 10000:
# my code
a = sp.levene() # my variables
if a[1] < 0.05:
i = 0
continue
i = 1
# doing something
continue在回圈體的開頭重新啟動回圈,并且設定i = 0它現在處于與第一次迭代時相同的狀態。
uj5u.com熱心網友回復:
處理此問題的最簡單方法是:
while True:
for i in range(100000):
...
if a[1] < 0.05:
# this will exit out of the for loop, but the while
# loop will keep going
break
else:
....
# if we've successfully finished the "for" loop, then break out of
# the while loop
break
如果你的邏輯有點復雜:
done = False
while not done:
for i in range(100000):
...
if a[1] < 0.05:
# this will exit out of the for loop, but the while
# loop will keep going
break
else:
# set done to True if you've decided you don't need to perform
# the outer loop any more
other stuff
# likewise, set done to True if you're done with the outer while loop
uj5u.com熱心網友回復:
如果您不想使用 break else break,請以 Frank Yellin 的答案為基礎。
continueloop=True
while(continueloop):
for i in range (10000):
#my codes
a=sp.levene #my variables
if a[1] < 0.05:
#I want to restart for loop again
continueloop=True
else:
continueloop=False
#doing something
希望你能找到合適的答案!
uj5u.com熱心網友回復:
我認為您要做的是在回圈中使用該功能。如果陳述句失敗,則在 else 陳述句中使用新引數再次呼叫該函式。基本上,你想要在你的回圈上遞回就是我所理解的。
def RecursionFunc() #3) when this function is called code runs from here
for i in range (10000):
#my codes
a= sp.levene(#my variables)
if a[1] < 0.05:
RecursionFunc() #2) will make you jump to the top again basically calling itself
break #4) will exit the current loop
else:
RecursionFunc() # 1)This will be the first code that gets executed
遞回將使函式繼續運行,你可以用它做很多其他的事情。我知道你想打破回圈并再次運行你也可以在下一次遞回運行時更改“i”值。如果你給 recursionFunc(int i) 那么你基本上可以在下次運行時將你的 for 回圈設定為新的 I 值。可以做很多像這樣很酷的事情。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/505244.html
下一篇:cli批處理中的for回圈
