Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I split list from matrix in python?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading