I want to merge two arrays in python in a special way.
The entries with an odd index of my output array out
shall be the coresponding entries of my first input array in0
. The entries with an even index in out
shall be the coresponding entries of my second input array
in1
.
in0
, in1
and out
are all the same length.
Example:
The input arrays
in0 = [0, 1, 2, 3]
in1 = [4, 5, 6, 7]
shall be merge to the output array
out = [0, 5, 2, 7]
Is there a nicer way than to loop over the whole length of the inputs and fill my out
'by hand'?
You could use a list comprehension and select values from in0
on even indices and in1
on odd indices:
[in0[i] if i % 2 == 0 else in1[i] for i in range(len(in0))]
# [0, 5, 2, 7]
If you're happy to make full list copy, this is simple with slicing:
>>> in0 = [0, 1, 2, 3]
>>> in1 = [4, 5, 6, 7]
>>> out = in0[:]
>>> out[1::2] = in1[1::2]
>>> out
[0, 5, 2, 7]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With