簡體   English   中英

提取最小和最大x值Python

[英]Extracting minimum and maximum x-values Python

我已經編寫了一個函數,該函數將帶有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)),它將再次讀取整個文件。

任何提示都受到高度贊賞:)

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來找到min

您應該創建一個生成器:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM