2017-07-16 74 views
0

我試圖讓lowRain函數打印出月份中數組中的最小數字。 例如,當我運行rainInput函數中的循環並輸入這些數字(4,3,10,10,10,10,10,10,8,23,10)時,它將通過lowRain函數。當我嘗試返回產生最低雨量的月份時,我得到「12月份的最低降雨量爲10英寸。」如何打印出在python中使用字符串數組的最小數字?

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

爲什麼不使用字典? – bigbounty

+1

爲了充分利用Stackoverflowit對於【提出好問題】(http://stackoverflow.com/help/how-to-ask)很重要,它包括創建一個[Minimal,Complete,and Verifiable](http:/ /stackoverflow.com/help/mcve)示例。 –

+0

什麼是降雨量?發佈'lowRain'呼叫的一些例子 – RomanPerekhrest

回答

1

你,你之前定義的1號線的月份名稱,它總是會導致April陣列上使用lowMonth = min(month)。我猜,你想查哪個月有一個是以前輸入的最小降雨量,在這種情況下,你可以這樣做:如果你保持降雨量和月份的名字連在一起,那麼你可以使用

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 
+0

謝謝,你回答了我的問題。 – freddyal

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比較序列它爲了序列比較部件,在這種情況下第一降雨量然後月份名稱。結果將始終具有最小的降雨量,如果有多個月具有相同的最小降雨量,您將獲得按字母順序排序的第一個月。

相關問題