Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine elements from two lists

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'?

like image 735
user2699453 Avatar asked Feb 22 '19 16:02

user2699453


2 Answers

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]
like image 76
yatu Avatar answered Oct 16 '22 09:10

yatu


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]
like image 8
Chris_Rands Avatar answered Oct 16 '22 08:10

Chris_Rands