2017-12-24 12 views
0

모든 노드의 좌표 문자열이 있습니다. 기본적으로 문자열을 한 쌍의 좌표 (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 
+0

미안하지만 당신이 말하는 것을 이해할 수 없습니다. 자신을 다시 표현해 주시겠습니까? – oBit91

+0

나는 그것을 벌써 만들었다 :) 고마워. – Anna

답변

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 

을 지금 루프는 처음 5 개 노드

을 당신에게 결과를 줄 것이다 처음 5 개 라인에 대한 실행하면서
+0

그것은 작동합니다. 고마워. – Anna

+0

노드 4에서 노드로 읽으려면 어떻게해야합니까? 그러나 나는 "line! ="EOF 코드를 지우고 싶지 않습니다. 문자열의 끝에는 "EOF"라는 문자열이 있기 때문입니다. – Anna

+0

노드 4에서 끝 노드까지 읽는 것을 의미합니까 ?? – Jai

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