Rya Rya - 2 months ago 6
Python Question

create a list but getting a string?

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)


I am expected to get
['A','B','C','D','E',.....'N']
, but I get
A B C D E .....N
and it's not a list. I spent a lot of time debugging, but could not find the right way.

Answer

Each line you read will create a new list called nodes. You need to create a list outside this loop and store all the 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)
Comments