Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Cross 2 arrays
#1
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
Reply
#2
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/
dylan261999 likes this post
Reply
#3
Another, similar library is Toolz: https://pypi.org/project/toolz/.
Reply
#4
Smile 
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}") 
Reply
#5
Great sharing the similar things Dancepapa's pizzeria Dance
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to cross compile python for ARM ? pankaj 4 5,619 Mar-06-2019, 05:59 AM
Last Post: pankaj
  cross validate amilie1234 6 6,740 Feb-09-2017, 08:28 PM
Last Post: amilie1234

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020