2010-12-11 142 views
0

我已經寫了一個函數,它將帶有x,y座標的文件作爲輸入,並且只顯示python中的座標。我想工作多一點與座標,這裏是我的問題:提取最小和最大x值Python

例如讀取文件,我收到後:

32, 48.6 
36, 49.0 
30, 44.1 
44, 60.1 
46, 57.7 

,我想提取最小和最大的x值。

我的函數讀取該文件是這樣的:

def readfile(pathname): 
    f = open(sti + '/testdata.txt') 
    for line in f.readlines(): 
     line = line.strip() 
     x, y = line.split(',') 
     x, y= float(x),float(y) 
     print line 

我的想法是這樣創造與MIN()和最大新功能(),但作爲即時通訊很新的蟒蛇即時通訊有點卡住了。

,如果我的實例調用分鐘(ReadFile的(路徑名)),它只是再次讀取整個文件..

任何提示的高度讚賞:)

回答

1

您應該創建一個發電機:

def readfile(pathname): 
    f = open(sti + '/testdata.txt') 
    for line in f.readlines(): 
     line = line.strip() 
     x, y = line.split(',') 
     x, y = float(x),float(y) 
     yield x, y 

充分利用這裏的最小值和最大值很簡單:

points = list(readfile(pathname)) 
max_x = max(x for x, y in points) 
max_y = max(y for x, y in points) 
+2

找到最小值「減少」幾乎總是一個錯誤。這裏使用'max_x = max(x代表x,y代表點)'和'max_y = max(y代表x,y代表點)' – 2010-12-11 11:40:16

+0

謝謝,更新 – terminus 2010-12-11 11:42:29

+0

爲什麼要讀兩次文件?如果文件非常大,該怎麼辦? – robert 2010-12-11 13:20:07

4
from operator import itemgetter 

# replace the readfile function with this list comprehension 
points = [map(float, r.split(",")) for r in open(sti + '/testdata.txt')] 

# This gets the point at the maximum x/y values 
point_max_x = max(points, key=itemgetter(0)) 
point_max_y = max(points, key=itemgetter(1)) 

# This just gets the maximum x/y value 
max(x for x,y in points) 
max(y for x,y in points) 

通過將max替換爲min