Python在列表上进行计算并添加到列表中

时间:2016-03-06 22:49:03

标签: python-3.x

我试图在Python中运行一个模型,该模型将某些计算应用于列表中的3个项目,然后继续将这些计算应用于一定数量的迭代。

以下代码是我到目前为止所获得的代码。我是否需要使用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)    

1 个答案:

答案 0 :(得分: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)