con = np.array([[ 0, 0, 0, 0, 500, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 500, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0],
[ 0, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0,
500, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0]])
For this 4×18 matrix: In each row, I want to keep the value that more than 0 such as in first row 500 and 500
This is my current matrix:
newArr5=[]
for j in range (4):
for i in range (18):
if con[j][i] > 0:
newArr5.append(con[j][i])
But the output shows:
[500, 500, 1000, 500]
I am looking find the way to split list. When the second and fourth row, there is no grater than zero value, it should be [0]:
[[500, 500], [0], [1000,500], [0]]
>Solution :
You need to create a new result list for each row, not use the same list for the entire matrix.
newArr5 = []
for row in con:
above_zero = [x for x in row if x > 0] or [0]
newArr5.append(above_zero)
Or as a single list comprehension:
newArr5 = [[x for x in row if x > 0] or [0] for row in con]