2016-03-06 66 views
0

我试图在Python中运行一个模型,该模型将对列表中的3个项目应用某些计算,然后继续将这些计算应用于一组迭代次数。Python在列表中执行计算并将其添加到列表中

下面的代码是我到目前为止。我是否需要使用诸如modulo或index()来保持if/elif继续增长?或者我会更好地融入功能?

# Nonsense Model for Fish numbers ### 
''' Fish numbers, in 100,000 tonnes in coastal waters. Those in the North Sea 
    increase by 10% every year. 
Those in the Irish Sea increase by 15%. Those in the Channel are currently decreasing 
the difference by 5%. Also want a total for each year for 10 year prediction.''' 
#master list 
fish = [] 
#ask questions 
northFish = int(input('How many fish in first year the North Sea?')) 
irishFish = int(input('How many fish in first year the Irish Sea?')) 
channelFish = int(input('How many fish in first year in The Channel?')) 

# add to the list 
fish.extend((northFish,irishFish,channelFish)) 
# display the start 
print (fish) 
year = int(input('how many years would you like to model?')) 
#run the model 

for i in range(1,year): 
    newFish = [] 
    if i == 0: 
     n = fish[0] * 1.1 
     newFish.append(n) 
    elif i == 1: 
     ir = fish[1] * 1.15 
     newFish.append(ir) 
    elif i == 2: 
     c = fish[2] * 0.95 
     newFish.append(c)  

    fish.extend(newFish) # add generated list to the master list  
    #total = n + i + c  
    #print('The total for year', i, 'is', total) 
print(fish)  

回答

0

编辑:这是你如何也可以保存每年的趋势。列表fish包含当年的人口,列表fish_trend包含每年的鱼群。例如fish_trend[5][1]将在5年后返回爱尔兰鱼群。

# Nonsense Model for Fish numbers ### 
''' Fish numbers, in 100,000 tonnes in coastal waters. Those in the North Sea 
    increase by 10% every year. 
Those in the Irish Sea increase by 15%. Those in the Channel are currently decreasing 
the difference by 5%. Also want a total for each year for 10 year prediction.''' 
# master list 
fish = [] 
# ask questions 
northFish = int(input('How many fish in first year the North Sea?')) 
irishFish = int(input('How many fish in first year the Irish Sea?')) 
channelFish = int(input('How many fish in first year in The Channel?')) 

# add to the list 
fish = [northFish, irishFish, channelFish] 
# display the start 
print(fish) 
year = int(input('how many years would you like to model?')) 
# run the model 

factors = (1.1, 1.15, 0.95) 

# initialize fish_trend with population of first year 
fish_trend = [tuple(fish)] 

# iterate through years 
for _ in range(year): 
    # iterate through fish types 
    for i in range(len(fish)): 
     fish[i] *= factors[i] 

    # append current population to fish_trend 
    fish_trend.append(tuple(fish)) 

# you can use pprint for better visualization 
import pprint 
pprint.pprint(fish_trend) 

# if you want the sum of the population per year, you can do that easily by using this: 
sum_per_year = [sum(f) for f in fish_trend] 

print(sum_per_year) 
+0

这只是给了我3个结果......十年来,我应该有30 ... –

+0

好吧,看我的编辑。你想达到什么目的? – Felix

+0

完美 - 你是明星!非常感谢:) –

相关问题