Updating a list according to another list in Python

Question:

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

[0, 2, 0, 6, 7, 9, 10]
Asked By: isaacmodi123

||

Answers:

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]

Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.