-3

I need help creating a new list z, where I will have list values as y0, x0, y1, x1, y2, x2, y3 in vertical order as an array.

output: z = [1, 1, 1, 0, 0, 2, 2, 2, 2, 4, 4, 3, 3, 3, 8, 8, 4, 4, 4]

I tried this for loop iteration, but instead of the desired list z, I get only list values as y2, x2.

I really appreciate any help you can provide.

x = [[0, 0], [4, 4], [8, 8]]
y = [[1, 1, 1], [2, 2, 2], [3, 3, 3 ], [4, 4, 4]

for i in range (0, 3):
    z = [*y[i], *x[i]]
phoenix_dj
  • 25
  • 6
  • https://stackoverflow.com/questions/7946798/interleave-multiple-lists-of-the-same-length-in-python – Shavk with a Hoon Jul 27 '22 at 14:43
  • what happens when you have your last x ? Should the list continue with the remaining y or stop? Please provide the entire solution – minattosama Jul 27 '22 at 14:44
  • 1
    x and y doesn't have the same shape, can you provide the expected output? – RomainL. Jul 27 '22 at 14:44
  • You overwrite `z` in every iteration, why do you expect it to contain the values it did previously? If you meant to _extend_ or _append to_ `z`, then use the `list.extend` or `list.append` functions. – Pranav Hosangadi Jul 27 '22 at 14:44

2 Answers2

2

Solution without for loop, first use zip_longest zipped the two lists, chain the results of per loop with chain.from_iterable, and then flattened them with list(chain.from_iterable(iterable_of_list)):

>>> from itertools import chain, zip_longest
>>> list(chain.from_iterable(map(chain.from_iterable, zip_longest(y, x, fillvalue=()))))
[1, 1, 1, 0, 0, 2, 2, 2, 4, 4, 3, 3, 3, 8, 8, 4, 4, 4]

Or use reduce and iconcat to flatten:

>>> from functools import reduce
>>> from operator import iconcat
>>> reduce(iconcat, map(chain.from_iterable, zip_longest(y, x, fillvalue=())), [])
[1, 1, 1, 0, 0, 2, 2, 2, 4, 4, 3, 3, 3, 8, 8, 4, 4, 4]
Mechanic Pig
  • 6,756
  • 3
  • 10
  • 31
1

I found the solution as:

from heapq import merge
from itertools import count

x = [[1, 1, 1], [2, 2, 2], [3, 3, 3 ], [4, 4, 4]]
y = [[0, 0], [4, 4], [8, 8]]
counter = count()
z = np.hstack(list(merge(x, y, key=lambda x: next(counter))))
phoenix_dj
  • 25
  • 6