Merge chopped lists

I have a list with N items, and I slice it with a specific step, say 3:

slice0 = text[0::3]
slice1 = text[1::3]
slice2 = text[2::3]

After doing a separate processing, now I will need to combine them back in the same positions that were in the original list. Is there a similar (simple) way to do this?

Example:

L = [1,2,3,4,5,6] -> L0 = [1,4], L1 = [2,5], L2 = [3,6]

Then some processing (for example, multiply each list by 1, 2, and 3, respectively:

L0 = [1,4], L1 = [4,10], L2 = [9,18] 

Drain them back to their original position.

L = [1,4,9,4,10,18]

Thank.

+3
source share
4 answers

You can use the function zip()to combine them:

>>> l0 = [1,4]; l1 = [4,10]; l2 = [9,18]
>>> zip(l0, l1, l2)
[(1, 4, 9), (4, 10, 18)]
>>> [x for t in zip(l0, l1, l2) for x in t]
[1, 4, 9, 4, 10, 18]

Or use itertools.chain:

>>> from itertools import chain
>>> list(chain(*zip(l0, l1, l2)))
[1, 4, 9, 4, 10, 18]

In Python 3, where zipis a generator function, it itertools.chain.from_iterablemight be preferable, as others have already noted.

+5
source
>>> L0 = [1,4]
>>> L1 = [4,10]
>>> L2 = [9,18]
>>> [x for zipped in zip(L0, L1, L2) for x in zipped]
[1, 4, 9, 4, 10, 18]

, itertools.chain:

>>> from itertools import chain
>>> list(chain.from_iterable(zip(L0, L1, L2)))
[1, 4, 9, 4, 10, 18]
+4
>>> from itertools import chain
>>> l0, l1, l2, = [1,4], [4,10], [9,18]
>>> list(chain.from_iterable(zip(l0,l1,l2)))
[1, 4, 9, 4, 10, 18]
+2
L0 = [1,4]
L1 = [4,10] 
L2 = [9,18]

#returns a tuple

my_data = sum(zip(L0,L1,L2),())

#or if you need a list

my_data = list(sum(zip(L0,L1,L2),()))

:

>>> my_data
(1, 4, 9, 4, 10, 18)

:

>>> my_data
[1, 4, 9, 4, 10, 18]
0

All Articles