Python 创建列表但获取字符串?

Python 创建列表但获取字符串?,python,list,debugging,Python,List,Debugging,我希望得到['A','B','C','D','E',…'N'],但我得到abcde…..N,它不是一个列表。我花了很多时间调试,但找不到正确的方法。您阅读的每一行都将创建一个名为节点的新列表。您需要在此循环之外创建一个列表并存储所有节点 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("

我希望得到
['A','B','C','D','E',…'N']
,但我得到
abcde…..N
,它不是一个列表。我花了很多时间调试,但找不到正确的方法。

您阅读的每一行
都将创建一个名为节点的新列表。您需要在此循环之外创建一个列表并存储所有节点

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)

不太确定您最终想要完成什么,但这将打印您所说的您期望的内容:

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)

添加以下代码,以便输出 ['A','B','C','D','E','F','G','H','J','K','L','M','N']

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)   

我相信这就是你想要的:

//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)
您所做的错误是,对于您创建的每个子列表,您都在迭代该子列表并打印出内容

上面的代码使用列表理解来首先迭代
gfile
,并创建列表列表。然后用第二行压平列表。然后,返回展平列表

如果仍要按自己的方式执行,则需要一个局部变量来存储每个子列表的内容,然后返回该变量:

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']

将for循环中的打印替换为
打印节点
@MosesKoledoye它仍然不工作…hmmm“因为您从函数返回的值是上次打印的返回值。”这是什么意思?它返回
None
,因为根本没有返回值。Python没有神奇的自动返回最后一个表达式。哦,我明白了,也许我最近用了太多ruby了。我将编辑掉它,因为它是错误的。现在缩进:)我很惊讶我没有想到这一点。使用列表理解,而不是创建局部变量并返回该变量,这是一个很好的想法。@DrewDavis,谢谢。如果我看到有人在使用for循环,我要做的第一件事就是看看我是否能理解一个等价的列表,因为通常情况下,有一个,它会让你的代码看起来更干净。
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)