gpt4 book ai didi

python - 如何将变量的值与该变量的名称联系起来?

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

我正在为编程入门类(class)做作业,要求我创建一个程序,允许用户输入值列表(12 个月内每个月的降雨量)并计算总数、中值以及列表中的最低值和最高值。

到目前为止,我所拥有的有效,但我不知道如何使程序打印该值所关联的月份名称。也就是说,如果三月份的降雨量最低,我如何告诉它不仅打印变量 mar 表示的整数,而且还打印该变量的名称?从我在网上找到的信息来看,有人建议我也许应该使用字典而不是列表 - 但直到下周我们才会在类里面讨论字典,而练习所在的书中的章节都是关于列表的,所以我想我应该找到一种方法来用列表来做到这一点。

这是我到目前为止的代码:

def main():
jan= float(input('Please enter January rainfall'))
feb= float(input('Please enter Februrary rainfall'))
mar= float(input('Please enter March rainfall'))
apr= float(input('Please enter April rainfall'))
may= float(input('Please enter May rainfall'))
jun= float(input('Please enter June rainfall'))
jul= float(input('Please enter July rainfall'))
aug= float(input('Please enter August rainfall'))
sep= float(input('Please enter September rainfall'))
oct= float(input('Please enter October rainfall'))
nov= float(input('Please enter November rainfall'))
dec= float(input('Please enter December rainfall'))
yearly_rainfall = [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
total = sum(yearly_rainfall)
median = total / 12
print('The total rainfall for the year is', total)
print('The average monthly rainfall for the year is', median)
print('The month with the lowest rainfall was', min(yearly_rainfall))
print('The month with the highest rainfall was', max(yearly_rainfall))


main()

最佳答案

您可以简单地在列表中的最小值和最大值索引与另一个包含月份名称的列表之间建立关系。

calendarMonthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
#Get the index of the min value and use that index value to get the month name.
print('The month with the lowest rainfall was', min(yearly_rainfall), ', and that month is', calendarMonthNames[yearly_rainfall.index(min(yearly_rainfall))])

关于python - 如何将变量的值与该变量的名称联系起来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47482139/

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