I'm having issues having my code display the minimum and maximum values as months instead of values. The code at the bottom for min and max are placeholders but I'm not sure how to tackle this problem.
def main():
#List of months
rain_month = ['January', 'February', 'March',' April', \
'May', 'June', 'July', 'August', \
'September', 'October', 'November', 'December']
#Rainfall list
rainfall = []
#Creates rainfall list for months
index = 0
while index < 12:
print ("Enter rainfall for ", rain_month [index], ": ",sep='', end = '')
amount = float(input())
rainfall.append(amount)
index += 1
print()
#Total Rainfall
total = 0
for value in rainfall:
total += value
print("Total Rainfall:", sep="", end="")
print(format(total, ',.2f'))
#Average Rainfall
average = total / len(rainfall)
print("Average Rainfall: ", sep="", end="")
print(format(average, ',.2f'))
#Sort
rainfall.sort()
print(min(rainfall))
print(max(rainfall))
main()
So to get the respective index of a min
or max
value you could do something like:
index = rainfall.index(min(rainfall))
And since you know that the index will correctly lin up with your rain_month
list, you can use that index to find the month:
print(rain_month[rainfall.index(min(rainfall))])
However, a better way would be link your rain_months
and rainfall
by using a dict
structure. Since we'd like the dict
to be ordered we should probably used an OrderedDict
:
import collections
# This is how OrderedDicts are initalized, you give them a list with (key,value) tuples for the order.
rainfall = collections.OrderedDict(
[('January',0),('Feburary',0)]
)
# Do your computation, something like:
for month in rainfall:
rainfall[month] = input("Rainfall: ")
print(min(rainfall, key=rainfall.get))
print(max(rainfall, key=rainfall.get))
Also, if you're doing rainfall.sort()
, you can get min
from rainfall[0]
and max
from rainfall[-1]
. min
and max
do not require sorted lists. Also, if you do sort
you change the order of rainfall
, while not changing the order of rain_month
, meaning you can't use the first method I described to get the correct month.
My suggestion would either to be to remove that sort
, or use the second method.