I have a list with N elements, and I slice it using certain step, let’s say 3:
slice0 = text[0::3]
slice1 = text[1::3]
slice2 = text[2::3]
After doing some processing separatedly, now I’d need to merge them back in the same positions they were in the original list. Is there a similar (easy) way to do this?
Example:
L = [1,2,3,4,5,6] -> L0 = [1,4], L1 = [2,5], L2 = [3,6]
Then some processing (say multiply each list by 1, 2 and 3 respectively:
L0 = [1,4], L1 = [4,10], L2 = [9,18]
Merge them back to their original positions
L = [1,4,9,4,10,18]
Thank you.
You can use the
zip()function to join them back together:Or use
itertools.chain:In Python 3, where
zipis a generator function,itertools.chain.from_iterablemight be preferrable, as others have pointed out already.