简体   繁体   中英

Create single list from list of lists

From data = ["1,2","3,4"] I'm attempting to create a list of strings : ["1","2","3","4"]

Trying this code :

comb = []
for x in data:
    for(y in x.split(',')):
        comb.append(y)

returns :

  File "<ipython-input-46-20897dcf51a1>", line 4
    for(y in x.split(',')):
                          ^
SyntaxError: invalid syntax

As x.split(',') return a list of the parsed elements , in this context it should be a valid for loop ?

most performant: avoid append , extend : just do a list comprehension with 2 flat loops:

data = ["1,2","3,4"]
data_flat = [x for c in data for x in c.split(",")]

print(data_flat)

result:

['1', '2', '3', '4']

You have an extra paranthesis. Try

comb = []
for x in data:
    for y in x.split(','):
        comb.append(y)

You don't really need the inner loop.

In [1]: data = ["1,2","3,4"]

In [2]: comb=list()

In [3]: for d in data:
   ...:     comb.extend(d.split(","))
   ...:

In [4]: comb
Out[4]: ['1', '2', '3', '4']

You almost had it. You had the for right on the first one. It seems that the parens after the split confused you and made you revert to another programming language that puts parens around for and if criteria. By removing the extraneous parens from the for y , you can fix it.

In [22]: data = ["1,2","3,4"]
    ...:
    ...: comb = []
    ...:
    ...: for x in data:
    ...:     for y in x.split(','):
    ...:         comb.append(y)
    ...:

In [23]: comb
Out[23]: ['1', '2', '3', '4']

A one liner:

print([item for sublist in ["1,2","3,4"] for item in sublist.split(',')])

Output:

['1', '2', '3', '4']

But your code is absolutely fine.The problem was that extra brackets you gave in your for loop:

data = ["1,2","3,4"]

comb = []
for x in data:
    for y in x.split(','): #corrected
        comb.append(y)

print(comb)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM