2010-12-11 157 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