Python Forum

Full Version: Cross 2 arrays
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

With Matlab, I can run this easily :

a = [0 0 0 0 0]
b = [1 1 1 1]

a(1:1:end) = b
To obtain : a = [0 1 0 1 0 1 0 1 0]

How can I implement this with Python ?

Thanks
Something like this?
from itertools import zip_longest, chain


def interleave(a, b):
    return [x for x in chain(*zip_longest(a, b)) if x is not None]


a = [0, 0, 0, 0, 0]
b = [1, 1, 1, 1]


print(interleave(a, b))
print(interleave(b, a))
Output:
[0, 1, 0, 1, 0, 1, 0, 1, 0] [1, 0, 1, 0, 1, 0, 1, 0, 0]
There are functions named interleave and interleave_longest in more_itertools. This is not a standard library. You can read about it here:

https://pypi.org/project/more-itertools/
Another, similar library is Toolz: https://pypi.org/project/toolz/.
It's not straigtforward (and it might be improved), but it does the job quit fastly even for huge vectors :-).

import time
import numpy as np

n,m=1_000_000, 4_000_000
a=np.ones((n), dtype=int)
b=2*np.ones((m), dtype=int)

t0=time.time()
La=len(a)
Lb=len(b)
if (Lb<La):
    c=np.concatenate((a[:Lb], b))
    c=np.reshape(c, (Lb, 2), order='f')
    c=np.reshape(c, (2*Lb), order='c')
    c=np.concatenate((c, a[Lb::]))
elif (Lb>La):
    c=np.concatenate((a, b[:La]))
    c=np.reshape(c, (La, 2), order='f')
    c=np.reshape(c, (2*La), order='c')
    c=np.concatenate((c, b[La::]))
else:
    c=np.concatenate((a, b))
    c=np.reshape(c, (La, 2), order='f')
    c=np.reshape(c, (2*La), order='c')
t1=time.time()
print(f"Duration={t1-t0}") 
Great sharing the similar things Dancepapa's pizzeria Dance