2014-09-28 6 views
-1

그래서 나는이 두 가지 기능을 작동 시키려고 노력하고있다, 내가 sepretly 그들이 일을 할 때,하지만 내가 elif 함수를 사용하여 두 기능을 결합하면, 그것은 단지 1을 실행합니다 기능과 위치 목록을 출력하고, 오류가두 가지 기능을 txt 파일을 읽고, 엘프 사용

이 내 코드

my_file=open("test_graph_1.txt","r") 
x=[] 
y=[] 
nodenumber=[] 
positionx=[] 
positiony=[] 


for row in my_file: 

    value=row[:-1] 

    my_list=value.split(",") 

    if len(my_list)==3: 
     nodenumber.append(int(my_list[0])) 

     positionx.append(int(my_list[1])) 
     positiony.append(int(my_list[2])) 

     nodenumber1 =[(nodenumber[a],positionx[a],positiony[a]) for a i range(len(nodenumber))] 
     position_list=tuple(nodenumber1) 




    elif len(my_list)==2: 
     x.append(int(my_list[0])) 
     y.append(int(my_list[1])) 

     l1 = [(x[i] , y[i]) for i in range(len(x))] 
     l2 = [(y[i] , x[i]) for i in range(len(x))] 
     l1.extend(l2) 
     neighbour_list=[[l[0] for l in l1 if l[1] == j] for j in range(len(x))] 


print("position_list",position_list) 
print("neigh",neighbour_list) 

이다 "는 neighbour_list가 정의되어 있지 않습니다"라고하지만 난 코드를 인쇄 할 때 위치 목록 잘 넣어 온다 그러나 neighbour_list이 나온다 [[4,1], [0, 4, 2], [1,3], [2, 5, 4], [3,0,1], [3] []] 거기에 있지 않다고 가정하지만 그 전에는 모두 괜찮음

+0

그렇다면 기능은 어디에 있습니까? – Kasramvd

+0

미안하지만, 아직 언어에 대한 핸들이 없다는 것은 2 가지 다른 if 루프가 position_list와 neighbour_list를 얻는 것을 의미합니다. – 13python

+1

else else my_list [2] == "":는 SyntaxError를 발생시켜야합니다. '엘프 ...? '라는 뜻 이었습니까? (또는 그냥'else :'?) – unutbu

답변

0

루프를 통과 할 때마다 my_list[2] != ""이 참이면 neighbour_list이 정의되지 않습니다. 그 다음

print("neigh",neighbour_list) 

으로 변경하면 NameError: the neighbour_list is not defined가됩니다.


대신, for-loop에 들어가기 전에 neighbour_list을 정의합니다. 나타날 것으로 예상되는 두 가지 유형의 선을 처리하려면

if len(my_list) == 3: 
    ... 
elif len(my_list) == 2: 
    ... 
else: 
    ... 

을 사용할 수도 있습니다.


N = 5 
position_list = list() 
neighbour_list = [list() for j in range(N)] 

with open("test_graph_1.txt","r") as my_file: 
    for row in my_file: 
     try: 
      my_list = map(int, row.split(',')) 
     except ValueError: 
      # Choose how to handle malformed lines 
      print('invalid line: {!r}'format(row)) 
      continue 
     if len(my_list) == 3: 
      nodenumber, positionX, positionY = my_list 
      position_list.append(tuple([nodenumber,positionX,positionY])) 
     elif len(my_list) == 2: 
      nodenumber1, nodenumber2 = my_list 
      neighbour_list[nodenumber1].append(nodenumber2) 
      neighbour_list[nodenumber2].append(nodenumber1)    
     else: 
      # Choose how to handle lines with more than 3 or less than 2 items 
      continue 

print(position_list) 
print("neigh", neighbour_list) 

는 또한 networkx 또는 igraph 같은 그래프 라이브러리를 사용 할 수 있습니다.

+0

그래 그게 무슨 일이야, 어떻게 해결할 수 있을까? – 13python

+0

당신은 neighbour_list에 값을 할당해야합니다. 당신은 당신의 프로그램이하기로되어있는 것을 말하지 않았으므로, 우리는 그것을 정말로 도울 수 없습니다. –

+0

'for-loop' 앞에'neighbour_list'의 값을 정의 할 수 있습니다. 'elif-suite'가 결코 도달하지 않을 때 프로그램이하기를 원하는 것에 따라 빈리스트 나'None'으로 설정할 수 있습니다. – unutbu