Suppose I have some list of column like this:
res = [[2],[3, 4],[0],[5]]
Then, I need to change this zr zero matrix 4X4 to be 1 following column in res list above; For example: the first row plots 1 in column 2, the second row plots 1 in column 3 and 4, the third row will have no plot due to [0] and the fourth row plots 1 in column 5.
zr = np.array([[0, 0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0, 0 ]]
Target:
zr = np.array([[0, 1, 0, 0, 0, 0,],
[0, 0, 1, 1, 0, 0,],
[0, 0, 0, 0, 0, 0,],
[0, 0, 0, 0, 1, 0 ]]
My current coding has a wrong change when some members in res equal to [0]:
for i, x in enumerate (res):
if x==0:
continue
else:
for j in x:
zr[i][j-1] = 1
Do you have any suggestions? Thank You.
>Solution :
Here’s what you want to do. This will skip the line if it finds [0] as an inner list.
for i, x in enumerate (res):
if x == [0]:
continue
else:
for j in x:
zr[i][j-1] = 1
print(zr)
Output:
[[0 1 0 0 0 0]
[0 0 1 1 0 0]
[0 0 0 0 0 0]
[0 0 0 0 1 0]]
What you were doing wrong is you were trying to compare x (which is a list) with 0. That’s always False.