这是我到目前为止的代码,有适当的缩进但我不知道如何在这里做。我试图用最大和最小降雨量打印月份,但到目前为止我只打印最大/最小降雨量的指数。例如。我正在尝试打印:'Highest rainfall: 45 mm in January'
和'Lowest rainfall: 12 mm in March'
。但到目前为止,我只是打印'Highest rainfall: 2 (index of max in rain)'
,而不是月份。
def main():
rains = []
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
for month in range(12):
rain = eval(input('Enter the amount of rain for ' + months[month] + ': '))
rains.append(rain)
total = sum(rains)
average = (total/len(rains))
print()
print('The Rain Amounts:')
print(rains)
print()
print('Total Rainfall:', (round(total,2)), 'mm.')
print('Average Rainfall:', (round(average,2)),'mm.')
print('Highest rainfall:', rains.index(max(rains)), 'mm in', months.index(rains.index(max(rains))))
print('Lowest rainfall:', rains.index(min(rains)), 'mm in', months.index(rains.index(min(rains))))
main()
答案 0 :(得分:0)
像这样:
import operator
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
rains = [12, 11, 10, 9, 8, 7, 6, 5, 4, 4, 2, 1]
index, value = max(enumerate(rains), key=lambda p: p[1])
print "Month with max rain: " + months[index]
index, value = min(enumerate(rains), key=lambda p: p[1])
print "Month with min rain: " + months[index]
输出:
Month with max rain: January
Month with min rain: December
答案 1 :(得分:0)
max_rain = max(rains)
max_rain_months = [months[i] for i,amt in enumerate(rains) if amt == max_rain]
print("Highest rainfall:", max_rain, "mm in", ', '.join(max_rain_months))
类似于min
。