![](/img/trans.png)
[英]Running a function in each iteration of a loop as a new process in python
[英]Calling a function to obtain a new value for each iteration of a loop in Python
我編寫了一個函數getSteps()
,該函數使用隨機包,該函數每次都應返回一個不同的值(當我多次手動運行該函數時會返回一個不同的值)。
但是,當我在for循環或while循環中調用它時,腳本只調用一次函數,然后將第一次迭代返回的值用於此后的每次迭代。
我試圖按以下方式調用該函數:
F = open("outFile.txt","w")
for i in range(6,100): ## for each of these values
for j in range(0,100): ## call the function 100 times
steps = getSteps(i)
F.write(str(i)+","+str(steps)+"\n")
對於每次迭代,它應該具有不同的值,但是我發現每一個都是相同的。 誰能告訴我該如何解決?
該函數定義如下:
def getSteps(maxSteps):
global numberSteps, numberAttempts, found
while (found == False):
sourceJar = psj[random.randrange(0, len(psj))]
if sourceJar in pdj:
pdj.remove(sourceJar)
destJar = pdj[random.randrange(0, len(pdj))]
if sourceJar == 8 and destJar == 5:
etf()
elif sourceJar == 8 and destJar == 3:
ett()
elif sourceJar == 5 and destJar == 8:
fte()
elif sourceJar == 5 and destJar == 3:
ftt()
elif sourceJar == 3 and destJar == 8:
tte()
elif sourceJar == 3 and destJar == 5:
ttf()
found = checkFound()
outString = "Pour the " + str(sourceJar) + " litre jar into the " + str(
destJar) + " litre jar. The volumes for each jar are now "
outString += "8-" + str(jar8volume) + ",5-" + str(jar5volume) + ",3-" + str(jar3volume)
##print outString
updateLists()
if (numberSteps >= maxSteps):
numberAttempts += 1
reset()
##print "Currently on iteration number " + str(numberAttempts)
numberSteps += 1
return numberAttempts + 1
您沒有顯示很多代碼。 但是大概的問題是您在getSteps
使用了全局變量; 一旦found
則在第一次調用時將其設置為True,它將保持為true,並且if
塊中的任何代碼都不會在后續調用中執行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.