2016-09-30 87 views
-1
s = """ 
1:A,B,C,D;E,F 
2:G,H;J,K 
&:L,M,N 
""" 

def read_nodes(gfile): 
    for line in gfile.split(): 
     nodes = line.split(":")[1].replace(';',',').split(',') 
     for node in nodes: 
      print node 

print read_nodes(s) 

我預計會得到['A','B','C','D','E',.....'N'],但我得到A B C D E .....N,它不是一個列表。我花了很多時間調試,但找不到正確的方法。創建一個列表,但得到一個字符串?

+1

在for循環更換打印'print節點' –

+0

@MosesKoledoye它仍然無法正常工作...嗯 – Rya

回答

0

你讀的每個line都會創建一個名爲nodes的新列表。您需要在此循環外創建一個列表並存儲所有節點。

s = """ 
1:A,B,C,D;E,F 
2:G,H;J,K 
&:L,M,N 
""" 

def read_nodes(gfile): 

    allNodes = [] 
    for line in gfile.split(): 
     nodes =line.split(":")[1].replace(';',',').split(',') 

     for node in nodes: 
      allNodes.append(node) 

    return allNodes 

print read_nodes(s) 
+1

「因爲從函數返回的值是最後一次打印的返回值。」你是什​​麼意思?它返回'None',因爲根本沒有返回值。 Python沒有神奇的自動返回最後表達式的東西。 – L3viathan

+1

哦,我明白了,也許我最近使用了太多的紅寶石。我會編輯它,因爲它是錯誤的。 – LucasP

0

不太清楚你最終要完成的,但是這將打印你說你期待:

s = """ 
1:A,B,C,D;E,F 
2:G,H;J,K 
&:L,M,N 
""" 

def read_nodes(gfile): 
    nodes = [] 
    for line in gfile.split(): 
     nodes += line.split(":")[1].replace(';',',').split(',') 
    return nodes 

print read_nodes(s) 
0

添加以下代碼,使輸出 [「A」, 'B','C','D','E','F','G','H','J','K','L','M','N']

//Code to be added 
nodes_list = [] 

def read_nodes(gfile): 

    for line in gfile.split(): 
     nodes =line.split(":")[1].replace(';',',').split(',') 
     nodes_list.extend(nodes) 
    print nodes_list 

print read_nodes(s) 
+0

現在縮進:) – anilkumarnandamuri

1

我相信這就是你要找的東西:

s = """ 
1:A,B,C,D;E,F 
2:G,H;J,K 
&:L,M,N 
""" 

def read_nodes(gfile): 
    nodes = [line.split(":")[1].replace(';',',').split(',') for line in gfile.split()] 
    nodes = [n for l in nodes for n in l] 
    return nodes 

print read_nodes(s) # prints: ['A','B','C','D','E',.....'N'] 

你做錯了什麼是你創建的每個子列表,你正在遍歷該子列表並打印出內容。

上面的代碼使用列表理解首先遍歷gfile並創建一個列表的列表。該列表隨後在第二行中展開。之後,返回平展列表。

如果你還想做你的方式,那麼你需要一個局部變量來存儲每個子列表中的內容,然後返回變量:

s = """ 
1:A,B,C,D;E,F 
2:G,H;J,K 
&:L,M,N 
""" 

def read_nodes(gfile): 
    all_nodes = [] 
    for line in gfile.split(): 
     nodes = line.split(":")[1].replace(';',',').split(',') 
     all_nodes.extend(nodes) 
    return all_nodes 

print read_nodes(s) 
+1

我很驚訝我沒有想到這一點。使用列表理解的好想法,而不必創建局部變量並返回該變量。 – Mangohero1

+0

@DrewDavis謝謝。如果我看到有人使用for循環,我試圖做的第一件事是看看我能否做出等效的列表理解,因爲通常會有一個,因此它會讓你的代碼看起來更清晰。 –

相關問題