Reputation: 627
I'm very new to python so i would appreciate any help I can get. How can I rearrange A to look like B?
A=([3,5,6,9,0,0,0,0,0])
B=([0,0,3,0,5,6,0,0,9])
Specifically, I want to rearrange A using the the entries as an index. So I want the 3rd, 5th, 6th, and 9th elements of B to be the value of that index.
Upvotes: 0
Views: 182
Reputation: 2532
I assume that you don't have any duplicate element in A or the element that is larger than the length of the list A. Then, using list comprehension,
B = [ i if i in A else 0 for i in range(1,10) ]
would work.
First, a list comprehension
[i for i in range(1,10)]
gives [1, 2, 3, 4, 5, 6, 7, 8, 9]
. You want to put 0
if an element in this list does not belong to the list A
. Thus, you replace the first i
in the list comprehension to i if i in A else 0
. It means that i
is left alone if it belongs to A
, orelse substitute 0
.
Upvotes: 2
Reputation: 375535
Since this is tagged numpy, here's a numpy solution:
In [11]: A = np.array([3,5,6,9,0,0,0,0,0])
Extract the poisition of the nonzero elements in A:
In [12]: np.nonzero(A)[0]
Out[12]: array([0, 1, 2, 3])
In [13]: ind = A[np.nonzero(A)[0]]
Trimming the zeroes may be equivalent (depending on the rules of the game):
In [14]: np.trim_zeros(A)
Out[14]: array([3, 5, 6, 9])
Create a B of zeroes and then fill with ind:
In [15]: B = np.zeros(A.max() + 1)
In [16]: B[ind] = ind
In [17]: B
Out[17]: array([ 0., 0., 0., 3., 0., 5., 6., 0., 0., 9.])
Upvotes: 4