Python Forum
Cross 2 arrays - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Cross 2 arrays (/thread-39382.html)



Cross 2 arrays - dylan261999 - Feb-08-2023

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


RE: Cross 2 arrays - deanhystad - Feb-08-2023

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/


RE: Cross 2 arrays - ndc85430 - Feb-09-2023

Another, similar library is Toolz: https://pypi.org/project/toolz/.


RE: Cross 2 arrays - paul18fr - Feb-09-2023

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}") 



RE: Cross 2 arrays - thensun - Feb-09-2023

Great sharing the similar things Dancepapa's pizzeria Dance