Search code examples
pythonlistcoordinate

Pick up some first coordinate lists from list pool


I have a string of coordinates of all nodes. Basically, I split the string into a pair of coordinates(x,y) (This is the result of part in the code: values = line.split() ). If I print "values", I will have the result as bellows:

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

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

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

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

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

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

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

I have 7 nodes with their coordinates. However I want to use the first 5 nodes to continue to append to coordinate list. How I can do it?

My code is:

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

Solution

  • change your code as follows:

    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
    

    Now you while loop will only run for first 5 lines which will give you results for first 5 nodes