Posts: 1
Threads: 1
Joined: Feb 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
Posts: 6,779
Threads: 20
Joined: Feb 2020
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
Posts: 1,838
Threads: 2
Joined: Apr 2017
Feb-09-2023, 04:44 AM
(This post was last modified: Feb-09-2023, 04:45 AM by ndc85430.)
Another, similar library is Toolz: https://pypi.org/project/toolz/.
Posts: 299
Threads: 72
Joined: Apr 2019
Feb-09-2023, 09:36 AM
(This post was last modified: Feb-09-2023, 09:37 AM by paul18fr.)
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}")
Posts: 1
Threads: 0
Joined: Feb 2023
Feb-09-2023, 01:06 PM
(This post was last modified: Feb-09-2023, 01:07 PM by thensun.)
Great sharing the similar things papa's pizzeria
|