2016-06-11 99 views
1

我正在運行一個人口模型,並且總是出現錯誤的數字,因爲我將變量設置爲新值,但是當我想使用舊變量時,循環自動更新自己並使用新的。使用計算在while循環中設置新變量PYTHON

juvenile_population = 10 
adult_population = 10 
senile_population = 1 
juvenile_survival = 1 
adult_survival = 1 
senile_survival = 0 
birth_rate = 2 
generations = 5 


counter = 0 
while counter < generations: 
    juvenile_population = adult_population * birth_rate 
    adult_population = juvenile_population * juvenile_survival 
    senile_population = (adult_population * adult_survival) (senile_population * senile_survival) 
    total_population = juvenile_population + adult_population + senile_population 



    print("Juvenile: ",juvenile_population) 
    print("Adult: ",adult_population) 
    print("Senile: ",senile_population) 
    print("Total: ",total_population) 
    counter += 1 

一位朋友說要設置新的命名變量,但是在一個循環之後,你會不會再次遇到同樣的問題?我希望變量能夠更新,但只有在它們已經被打印之後,如果這是有意義的。 有什麼建議嗎?

+0

最簡單的方法是你的朋友建議:使用新變量進行存儲和打印,然後在完成打印時將它們分配給舊變量。否則,您可以使用答案中給出的建議,並立即進行所有計算 – Aquiles

+0

感謝您的澄清+關於我的朋友對新變量所說的更多提示。我的代碼正在工作:) – Ollie

回答

0

每@Selcuk,你可以直接使用變量拆包,但即使有更好的格式,它看起來笨拙:

juvenile_population, adult_population, senile_population, total_population = (adult_population * birth_rate, 
                      juvenile_population * juvenile_survival, 
                      (adult_population * adult_survival) (senile_population * senile_survival), 
                      juvenile_population + adult_population + senile_population) 

我的建議是要麼寫一個輔助功能,並保持「喜歡」的價值觀這樣的字典:

populations = {'juvenile': 10, 
       'adult':  10, 
       'senile': 1 
       } 
survivals = {'juvenile': 1, 
      'adult':  1, 
      'senile':  0} 
birth_rate = 2 
generations = 5 

def update_population(pops): 
    juvie = pops['adult'] * birth_rate 
    adults = pops['juvenile'] * survivals['juvenile'] 
    seniles = pops['adult'] * survivals['adult'] + (pops['senile'] * survivals['senile']) 
    return {k:v for k,v in zip(['juvenile','adult','senile'],[juvie,adults,seniles])} 

counter = 0 
while counter < generations: 
    populations = update_population(populations.copy()) 
    total_population = sum(populations.values()) 



    print("Juvenile: ",populations['juvenile']) 
    print("Adult: ",populations['adult']) 
    print("Senile: ",populations['senile']) 
    print("Total: ",total_population) 
    counter += 1 
1

您正在用新值覆蓋現有值。使用Python可以將所有四行合併成一個像這樣的:

juvenile_population, adult_population, senile_population, total_population = adult_population * birth_rate, juvenile_population * juvenile_survival, (adult_population * adult_survival) (senile_population * senile_survival), juvenile_population + adult_population + senile_population 

這將在一次分配中的所有值,而不首先覆蓋它們。