Reputation: 11
in Matlab, array[] = [1 2 3 4 5 6], we can have operation like :
array= [zeros(1,3) tones(3:6) zeros(1,1) tones(1:2) zeros(1,5)];
array[] = [0 0 0 3 4 5 6 0 1 2 0 0 0 0 0]
is there any similiar way in python to make it happen?
Upvotes: 0
Views: 43
Reputation: 15872
The exact array like version for Python may be:
>>> array = np.hstack((np.zeros(3),np.arange(3,7),np.zeros(1),np.arange(1,3),np.zeros(5)))
>>> array
array([0., 0., 0., 3., 4., 5., 6., 0., 1., 2., 0., 0., 0., 0., 0.])
Upvotes: 0
Reputation: 7206
you can get the same result using:
'*
' unpacking operator
slicing or range
defining list of n elements
code:
arr = [1,2,3,4,5,6]
print ([*[0]*3 , *arr[2:6], *[0]*1, *arr[0:2], *[0]*5])
print ([*[0]*3 , *range(3,7), *[0]*1, *range(1,3), *[0]*5])
output:
[0, 0, 0, 3, 4, 5, 6, 0, 1, 2, 0, 0, 0, 0, 0]
Upvotes: 1
Reputation: 381
a = [0 for i in range(3)] + [i for i in range(3,7)]
+[0 for i in range(1)] + [i for i in range(1,3)]
+[0 for i in range(5)]
Output:
[0, 0, 0, 3, 4, 5, 6, 0, 1, 2, 0, 0, 0, 0, 0]
Upvotes: 0
Reputation: 17166
x = [0]*3 + list(range(3, 7)) + [0] + list(range(1,3)) + [0]*5
print(x) # [0, 0, 0, 3, 4, 5, 6, 0, 1, 2, 0, 0, 0, 0, 0]
Upvotes: 1