我正在尝试使用lowRain函数打印月份中数组中的最小数字。 例如,当我在rainInput函数中运行循环并输入这些数字(4,3,10,10,10,10,10,10,10,8,23,10)时,它将通过lowRain函数。当我试图返回产生最低降雨量的月份时,我得到的最低降雨量为12英寸。"
def main():
rainfall = rainInput()
low, lowMonth = lowRain(rainfall)
print("The lowest rainfall for " + str(low) + " was " + str(lowMonth) + " inches.")
def rainInput():
rainfall = ["January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
for month in range(len(rainfall)):
rainfall[month] = (int(input("Please enter the amount of rain for " + str(rainfall[month]) + " :")))
return rainfall
def lowRain(rainfall):
month = ['January','Febuary','March','April','May','June','July','August','September','October','November','December']
lowMonth = min(month)
print(lowMonth)
for m, n in enumerate(rainfall):
if lowMonth:
lowMonth = n
low = m
return month[low], lowMonth
main()
答案 0 :(得分:1)
您在之前1行定义的月份名称数组上使用lowMonth = min(month)
,这将始终生成April
。我猜你想检查哪个月有最小的降雨量,在这种情况下你可以这样做:
def lowRain(rainfall):
lowest = min(rainfall)
index_of_lowest = rainfall.index(lowest)
month = ['January','Febuary','March','April','May','June','July','August','September','October','November','December']
lowest_month = month[index_of_lowest]
return lowest_month, lowest
答案 1 :(得分:0)
如果您将降雨量和月份名称保持在一起,则可以使用min
功能:
>>> data
[(4, 'January'),
(3, 'Febuary'),
(10, 'March'),
(10, 'April'),
(10, 'May'),
(10, 'June'),
(10, 'July'),
(10, 'August'),
(10, 'September'),
(8, 'October'),
(23, 'November'),
(10, 'December')]
>>> min(data)
(3, 'Febuary')
这是因为当min
比较序列时,它按顺序比较序列成分,在这种情况下首先是降雨量,然后是月份名称。结果将总是具有最小的降雨量,并且如果有多个月具有相同的最小降雨量,那么您将获得按字母顺序排序的第一个月。