Home > OS >  how to flatten 2D list and add a separator character using zip and list comprehension in python?
how to flatten 2D list and add a separator character using zip and list comprehension in python?

Time:03-29

I'm trying to write a statement in python that turns this input (for example):

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

into this output:

 [3,4,-,1,-,1,2]

using only zip and list comprehension

this is my code:

a = [[1,2],[1],[3,4]]
result = [j for i in zip(a,'-'*len(a)) for j in i]

print(result)

but all I get is:

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

and my output should be this:

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

what am I missing?

CodePudding user response:

You can do something like that:

a = [[3,4],[1],[1,2]]

result = []
for i,l in enumerate(a):
    result  = l   ["-"] * (i!=len(a)-1)

print(result) # [3, 4, '-', 1, '-', 1, 2]

CodePudding user response:

you almost got it, just use the itertools library:

# import chain
from itertools import chain

a = [[1,2],[1],[3,4]]
result = [j for i in zip(a,'-'*len(a)) for j in i]
flatten_list = list(chain.from_iterable(result))

print (str(flatten_list))

and your output:

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

CodePudding user response:

This should work:

a = [[1,2],[1],[3,4]]
result = [a for i in zip(a,'-'*len(a)) for j in i for a in j]
print(result)

Output:

[1, 2, '-', 1, '-', 3, 4, '-']
  • Related