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

时间:2017-11-25 02:33:32

标签: python

我正在编写一个编程课程简介的家庭作业,要求我创建一个程序,允许用户输入一个值列表(每个12个月的降雨量)并计算总数,中位数,以及列表中的最低和最高值。

到目前为止我的工作原理,但我不知道如何让程序打印出与该值绑定的月份的名称。也就是说,如果March有最低的降雨量,我怎么告诉它不仅打印变量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()

1 个答案:

答案 0 :(得分:1)

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

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))])