2014-09-28 82 views
-1

所以我一直在試圖讓這兩個函數工作,當我做他們的工作,他們sepretly,但是當我結合使用elif函數的兩個函數,它只運行第1功能和打印出位置列表,以及一個錯誤說「的neighbour_list沒有定義」兩個函數讀取一個txt文件,使用elif

這是我的代碼

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出來像這樣:[[4,1],[0,4,2],[1,3],[2,5,4],[3,0,1],[3],[]] 額外的空字符串,這是不假設在那裏,但在這之前,一切都很好

+0

那麼你的功能在哪裏? – Kasramvd 2014-09-28 13:14:00

+0

對不起,我還沒有處理語言,我的意思是我的2個不同的循環獲取position_list和neighbour_list – 13python 2014-09-28 13:16:17

+1

'else my_list [2] ==「」:'應該引發了一個SyntaxError。你是不是指「elif ...」? (或只是'else:'?) – unutbu 2014-09-28 13:16:53

回答

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) 

您可能還需要使用一個圖形庫像networkxigraph

+0

是的,這是發生了什麼,我將如何解決這個問題? – 13python 2014-09-28 13:22:27

+0

您必須爲neighbour_list分配一個值。你沒有說你的程序應該做什麼,所以我們不能真正幫助。 – 2014-09-28 13:24:17

+0

你可以在'for-loop'之前的頂部附近爲'neighbour_list'定義一個值。您可以將它設置爲空列表或「無」,具體取決於程序在永遠不會到達'elif-suite'時執行的操作。 – unutbu 2014-09-28 13:26:02