2016-09-30 30 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循环,我试图做的第一件事是看看我能否做出等效的列表理解,因为通常会有一个,因此它会让你的代码看起来更清晰。 –

相关问题