1

I wrote a program that does the job, however it is not very pythonic, not pythonic and definitly not beautiful.

The program must concatenate two numpy arrays in the following manner:

As an example list0 and list1 are the input

list0 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list1 = [ 2,  3,  4,  5,  6,  7,  8,  9, 10, 11]

The output should look like the following:

[0, 2, 1, 3, 2, 4, 3, 5, 4, 6, 5, 7, 6, 8, 7, 9, 8, 10, 9, 11]

So basically put in the number of list0 at every even point of the output, and put in the number of list1 at every uneven point.

I am fairly new to python so I wrote it in a C-Style:

import numpy as np



list0 = np.arange(10)
list1 = np.arange(2,12)

new = []
cnt0 = 0
cnt1 = 0
for i in range(0,2*len(list0)):
    if i % 2 == 0:
        new.append(list0[cnt0])
        cnt0 = cnt0 +1;
    else:
        new.append(list1[cnt1])
        cnt1 = cnt1 +1;

Now I want to know if there is a more fancy, pythonic, faster way to achieve the same goal?

Kev1n91
  • 3,553
  • 8
  • 46
  • 96

3 Answers3

2

Being NumPy tagged, here's one with it -

np.vstack((list0, list1)).ravel('F').tolist()

ravel() here flattens in fortran order with the F specifier.

A shorter version with np.c_ that basically stacks the elements in columns -

np.c_[list0,list1].ravel().tolist()

ravel() here flattens in the default C order, so skipped here.

If the final output is to be kept as an array, skip the .tolist() from the approaches.

Divakar
  • 218,885
  • 19
  • 262
  • 358
1

Nice one liner with itertools

from itertools import chain

chain(*zip(list0, list1))

[0, 2, 1, 3, 2, 4, 3, 5, 4, 6, 5, 7, 6, 8, 7, 9, 8, 10, 9, 11]
user3684792
  • 2,542
  • 2
  • 18
  • 23
  • Thank you for reminding me of itertools, however I would prefer not to use any additional libraries – Kev1n91 Apr 20 '17 at 12:52
1

You can use zip

>>> output = [ data for elem in zip(list0,list1) for data in elem ]
[0, 2, 1, 3, 2, 4, 3, 5, 4, 6, 5, 7, 6, 8, 7, 9, 8, 10, 9, 11]
akash karothiya
  • 5,736
  • 1
  • 19
  • 29
  • Thank you, this answer is great since it does not need any further libs, however I made an edit to the post so it focus now on numpy array. Sry for the mislead. – Kev1n91 Apr 20 '17 at 12:53