Python平均降雨量,如何获得年平均值?

时间:2017-10-18 23:38:41

标签: python

在这个程序中,如果超过1,我会将它设置为获得所有年份的总体平均值,但是如何获得单独的年度平均值?

total_months = 0

rainfall_inches = 0

years = int(input("How many years of data do you wish to collect? "))

for currentYear in range(1, years + 1):

    for currentMonth in range(1, 13):

        monthly_rainfall = float(input("Enter the inches of rainfall for month " 
+ format(currentMonth, "d") + ", year " + format(currentYear,"d") + 
": "))

        rainfall_inches += monthly_rainfall

        total_months += 1


avg_rainfall = rainfall_inches / total_months

print("Number of months: " + format(total_months, "d"), "Total inches of `
rainfall: " + format(rainfall_inches, ".2f"), "Average rainfall: " + `
format(avg_rainfall, ".2f"), sep="\n")

1 个答案:

答案 0 :(得分:1)

一种方法是添加annual_avgs列表并在外部for循环中更新它,并从该列表中查找总平均值,而不是使用total_months。例如:

yearly_avgs = []                       # initialize list for yearly averages
total_months = 0
rainfall_inches = 0
years = int(input("How many years of data do you wish to collect? "))

for currentYear in range(1, years + 1):
  for currentMonth in range(1, 13):
    monthly_rainfall = float(input("Enter the inches of rainfall for month "
    + \
    format(currentMonth, "d") + ", year " + format(currentYear,"d") +
    ": "))
    rainfall_inches += monthly_rainfall
    total_months += 1
  yearly_avgs += rainfall_inches       # append average for currentYear
  rainfall_inches = 0                  # reset rainfall_inches

avg_rainfall = sum(yearly_avgs)/years  # get average over years

print("Number of months: " + format(total_months, "d"), "Total inches of `
rainfall: " + format(rainfall_inches, ".2f"), "Average rainfall: " + `
format(avg_rainfall, ".2f"), sep="\n")

它仍然有点笨拙,但我认为它完成了工作。