2014-02-12 35 views
1

我想從一個CSV文件中找到一組數字中的最大值和最小值。我的代碼爲某些行不斷返回Max函數的錯誤數字。這是我的代碼:Python中的最大功能返回錯誤的結果

file1 = open ('Cortex_vs_Liver_trial.csv', 'rb') 
    reader1 = csv.reader(file1) 

    next(reader1, None) # skip the headers 
    for col in reader1: 
     print (col[3:6]) 
     Max1 = max (col[3:6]) 
     Min1 = min (col[3:6]) 
     print 'The maximun is:', Max1 
     print 'The minimum is:', Min1 
     print col[6:9] 
     Max2 = max (col[6:9]) 
     Min2 = min(col[6:9]) 
     print 'The maximun is:', Max2 
     print 'The minimum is:', Min2 

    file1.close() 

我的輸出的〔實施例:

['82 0.61' ,'92 0.86' ,'50 0.00' ] 的maximun是:92.86 最小值爲:50.00

['86 0.21' , '100.00','96 0.30' ] 的maximun是:96.30 最小值爲:100.00

我不知道我做錯了。一些建議,將不勝感激。

謝謝。

+3

你比較字符串不是數字數據。使用:'max(col [3:6],key = float)' –

+0

非常感謝。像拼湊一樣工作! – user3302763

回答

3

您的列表元素是字符串。你需要將它們轉換爲float避免字典順序比較(按字母順序排列,一個字符時,其中'100' < '2'因爲1 < 2

intcol = [int(x) for x in col] 
Max1 = max(intcol[3:6]) 
Min1 = min(intcol[3:6]) 

除非你真正想要的字符串,在這種情況下,不要讓新的列表,只是通過key=floatmax()功能:

Max1 = max(col[3:6], key=float)