【问题标题】:Extracting minimum and maximum x-values Python提取最小和最大x值Python
【发布时间】:2010-12-11 19:48:28
【问题描述】:

我已经编写了一个函数,该函数将带有 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)) 它只是再次读取整个文件..

任何提示都非常感谢:)

【问题讨论】:

    标签: python


    【解决方案1】:
    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 来找到最小值

    【讨论】:

      【解决方案2】:

      你应该创建一个生成器:

      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)
      

      【讨论】:

      • 'reduce' 几乎总是一个错误。这里使用max_x = max(x for x, y in points)max_y = max(y for x, y in points)
      • 为什么要读取两次文件?如果文件非常大怎么办?
      猜你喜欢
      • 2014-10-17
      • 2021-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 2021-06-20
      • 2019-01-09
      相关资源
      最近更新 更多