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

Updating a list according to another list in Python

I have lists J and CB. I am updating J based on elements in CB but I want to insert 0 whenever CB[i]=[]. I present the current and expected outputs.

import numpy as np

J=[[1, 2, 4, 6, 7, 9, 10]]

CB=[[],
 [np.array([0.00351331]), np.array([0.0070412]), np.array([0.00352908])],
 [],
 [np.array([0.01067821])],
 [np.array([0.01070989])],
 [np.array([0.01067821])],
 [np.array([0.01070989])]]

J = [J[0][i] for i, a in enumerate(CB) if np.array(a).size != 0]
print(J)

The current output is

[2, 6, 7, 9, 10]

The expected output is

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

[0, 2, 0, 6, 7, 9, 10]

>Solution :

You need to use a conditional in your list comprehension, not a filter:

J = [J[0][i] if np.array(a).size != 0 else 0 for i, a in enumerate(CB)]
print(J)

Output: [0, 2, 0, 6, 7, 9, 10]

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