提取Python中的最小和最大x值

0 投票
2 回答
4103 浏览
提问于 2025-04-16 08:23

我写了一个函数,可以读取一个包含 x 和 y 坐标的文件,然后在 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() 和 max() 来实现,但因为我对 Python 还很陌生,所以有点卡住了。

如果我调用 min(readfile(pathname)),它就会重新读取整个文件……

任何建议都非常感谢:)

2 个回答

5
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 就可以了。

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)

撰写回答