如何打印出在 python 中使用字符串数组的最小数字?



我正在尝试让 lowRain 函数也打印出数组中带有月份的最小数字。 例如,当我在 rainInput 函数中运行循环并输入这些数字(4、3、10、10、10、10、10、10、8、23、10(时,它将通过 lowRain 函数。当我尝试返回降雨量最低的月份时,我得到"12 月的最低降雨量为 10 英寸"。

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

您正在之前定义的 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

如果将降雨量和月份名称放在一起,则可以使用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比较序列时,它会按顺序比较序列分量,在这种情况下,首先是降雨量,然后是月份名称。结果将始终具有最小降雨量,如果有多个月份具有相同的最小降雨量,您将获得按字母顺序排序中排在第一位的月份。

相关内容

  • 没有找到相关文章

最新更新