Can't change the code to list comprehension

Viewed 88

My question is kind of simple yet I don't seem to find the answer.

I have the following line in my code that works fine:

Uniquesample = np.matrix([[   1.   ,    0.   ],
                   [   2.   , -106.965],
                   [   3.   ,  -83.835],
                   [   4.   ,   12.5  ],
                   [   5.   , -141.6  ],
                   [   6.   ,  -17.25 ],
                   [   7.   ,  -94.785],
                   [   8.   ,  -26.785],
                   [   9.   , -125.835],
                   [  10.   ,    6.865],
                   [  11.   ,   16.23 ],
                   [  12.   ,   61.45 ],
                   [  13.   ,   42.625],
                   [  14.   , -163.655],
                   [  15.   , -116.3  ],
                   [  16.   ,   15.82 ],
                   [  17.   , -166.055],
                   [  18.   ,   90.025],
                   [  19.   ,   14.215],
                   [  20.   ,   82.465]])
L, W = Uniquesample.shape
ModelNumber = 8
Members = np.zeros((L,ModelNumber*W))

seq=[4, 7, 9, 2, 15, 16, 19]
i=0
Count = [7]
for j in seq:
    Members[:Count[i]:,W*i:W*(i+1)] = Uniquesample[j]

Ps: Uniquesample is a 800 x 2 matrix, so i only put the first 20 rows here for simplicity. I tried to change the for loop to another format using "list comprehension":

Members[:Count[i]:,W*i:W*(i+1)] = [Uniquesample[j] for j in seq]

But it does not work. I get the following error: "ValueError: setting an array element with a sequence. The requested array would exceed the maximum number of dimension of 2."

The thing is. Did I "translate" the code correctly to the list comprehension format?

Thank you very much

2 Answers

I used seq=[4, 7, 9, 2, 15, 16, 19] in below example. The initial Members array looks like this: enter image description here

In the for-loop, Members[:Count[i]:,W*i:W*(i+1)] = Uniquesample[j] will replace those 7x2 elements (in red) with the final value in for-loop.

enter image description here

However the list comprehension Members[:Count[i]:,W*i:W*(i+1)] = [Uniquesample[j] for j in seq] will assign each element differently.

enter image description here

FYI, I'm using numpy version '1.18.5', so it may not run properly on www.onlinegdb.com because of old numpy version.

enter image description here

The point is, in first code you are assigning one item of Uniquesample[j] each time in Members[:Count[i]:,Wi:W(i+1)]. First Uniquesample[0] to Members[:Count[i]:,Wi:W(i+1)], then Uniquesample[1] to same Members[:Count[i]:,Wi:W(i+1)] and so on.

In your second code you are trying to put a list of Uniquesample items into a location, which can only hold one item. That's why the error.

Related