gpt4 book ai didi

python - 使用列表获取平均值

转载 作者:太空宇宙 更新时间:2023-11-04 08:12:03 25 4
gpt4 key购买 nike

这个程序应该要求用户输入 12 个月的月降雨量,计算并计算全年降雨量、月平均降雨量以及最高和最低降雨量的月份。

我可以让它要求输入,给出每年的总计和每月的平均数,但我觉得好像程序的输入部分应该以某种方式减少,它看起来太大太笨重,我不能完全弄清楚如何获得高/低平均值。任何帮助将非常感激。提前致谢。

def main():
jan = int(input('Enter Rainfall For January: '))
feb = int(input('Enter Rainfall for February: '))
mar = int(input('Enter Rainfall For March: '))
april = int(input('Enter Rainfall For April: '))
may = int(input('Enter Rainfall For May: '))
june = int(input('Enter Rainfall For June: '))
jul = int(input('Enter Rainfall For July: '))
aug = int(input('Enter Rainfall For August: '))
sept = int(input('Enter Rainfall For September: '))
oct = int(input('Enter Rainfall For October: '))
nov = int(input('Enter Rainfall For November: '))
dec = int(input('Enter Rainfall For Deceember: '))
totalyear = jan + feb + mar + april + may + june + jul + aug + sept + oct + nov + dec
print('The total for the year is: ',totalyear)
avg = jan + feb + mar + april + may + june + jul + aug + sept + oct + nov + dec / 12
print('The average monthly rainfall is: ',avg)
main()

最佳答案

您可以使用列表和循环。 :)

def main():
months = ["Jan","Feb" .... ,"Dec"]
rain = []
for month in months:
rain.append(int(input("Enter .. for" + month)))
print("Total", sum(rain))
print("Average", sum(rain)/float(len(rain)))

同样,对于最大值和最小值,您可以使用 max(rain)min(rain)

关于python - 使用列表获取平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20537266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com