Extracting minimum and maximum x-values Python
i've written a function that takes a file with x,y coordinates as input, and simply show the coordinates in python. I want to work a bit more with the coordinates and here is my problem:
for example after reading a file i get:
32, 48.6
36, 49.0
30, 44.1
44, 60.1
46, 57.7
and i want to extract the minimum and the maximum x-value.
My function to read the file is like this:
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
i was thinking something like creating a new function with min() and max() but as im pretty new to python im a bit stuck.
if i for instance call min(readfile(pathname)) it just reads the whole file again..
开发者_如何学编程Any hints is highly appreciated:)
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)
minimum values are found by replacing max
with min
You should create a generator:
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
Getting the minimum and maximum from here on is easy:
points = list(readfile(pathname))
max_x = max(x for x, y in points)
max_y = max(y for x, y in points)
精彩评论