从列表池中选取一些第一个坐标列表

问题描述 投票:0回答:2

我有一串所有节点的坐标。基本上,我将字符串拆分为一对坐标(x,y)(这是代码中的部分结果:values = line.split())。如果我打印“值”,我将得到结果:

['1', '3600', '2300']

['2', '3100', '3300']

['3', '4700', '5750']

['4', '5400', '5750']

['5', '5608', '7103']

['6', '4493', '7102']

['7', '3600', '6950'] 

我有7个节点及其坐标。但是我想使用前5个节点继续追加到坐标列表。我怎么能这样做?

我的代码是:

def read_coordinates(self, inputfile):
    coord = []
    iFile = open(inputfile, "r")
    for i in range(6):  # skip first 6 lines
        iFile.readline()
    line = iFile.readline().strip()
    while line != "EOF":
        **values = line.split()**
        coord.append([float(values[1]), float(values[2])])
        line = iFile.readline().strip()
    iFile.close()
    return coord
python list coordinate
2个回答
0
投票

更改您的代码如下:

def read_coordinates(self, inputfile):
    coord = []
    iFile = open(inputfile, "r")
    for i in range(6):  # skip first 6 lines
        iFile.readline()
    line = iFile.readline().strip()
    i = 0
    while i < 5 
        values = line.split()
        coord.append([float(values[1]), float(values[2])])
        line = iFile.readline().strip()
        i += 1
    iFile.close()
    return coord

现在,while循环只会运行前5行,这将为前5个节点提供结果


0
投票

也许这将成功,使用上下文管理器来保持功能更加整洁。

def read_coordinates(self, inputfile):

    coord = []
    with open(inputfile, "r") as iFile:
        for i in xrange(6):  # Skip first 6 lines
            next(iFile)

        for i in xrange(5):  # Read the next 5 lines
            line = iFile.readline().strip()
            values = line.split()
            coord.append([float(values[1]), float(values[2])])
    return coord
© www.soinside.com 2019 - 2024. All rights reserved.