3

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?

Alex Butane
  • 127
  • 8

4 Answers4

1

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

This also works if you don't want the last '-' to be included:

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

Output:

[1, 2, '-', 1, '-', 3, 4]
catasaurus
  • 933
  • 4
  • 20
1

Adding another for clause and prepending the separator before each inner list except the first:

[k for i in zip([[]]+['-']*len(a), a) for j in i for k in j]

Result (Try it online!):

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

The zip(...) gives these three pairs:

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

Then j is the inner lists/strings, and k is the numbers/characters, so we can use k for the result elements of the list comprehension.

Pychopath
  • 1,560
  • 1
  • 8
0

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]
TKirishima
  • 742
  • 6
  • 18
-1

Here is a solution that reuse part of your code and just use the itertools library to achieve your goal:

# import chain
from itertools import chain

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

and your output:

[1, 2, '-', 1, '-', 3, 4]
ML1
  • 99
  • 1
  • 8