Removing elements from a list and modifying another list in Python
Question:
I have a list CB
containing many sublists with numpy arrays. I want to identify the empty lists and generate a new list J_new
by removing the specific element. I present the current and expected output.
import numpy as np
arJ_new=[]
CB = [[[]], [np.array([9.75016872e-05]), np.array([0.00019793]), np.array([0.0001007])], [np.array([0.0002704])]]
J=[32,1,35]
for i in range(0,len(CB)):
if len(CB[i])!=0:
J_new=J[i]
arJ_new.append(J_new)
J_new=list(arJ_new)
print(J_new)
The current output is
[32, 1, 35]
The expected output is
[1,35]
Answers:
By means of numpy
(check size) filtering:
j_new = [J[i] for i, a in enumerate(CB) if np.array(a).size != 0]
[1, 35]
I have a list CB
containing many sublists with numpy arrays. I want to identify the empty lists and generate a new list J_new
by removing the specific element. I present the current and expected output.
import numpy as np
arJ_new=[]
CB = [[[]], [np.array([9.75016872e-05]), np.array([0.00019793]), np.array([0.0001007])], [np.array([0.0002704])]]
J=[32,1,35]
for i in range(0,len(CB)):
if len(CB[i])!=0:
J_new=J[i]
arJ_new.append(J_new)
J_new=list(arJ_new)
print(J_new)
The current output is
[32, 1, 35]
The expected output is
[1,35]
By means of numpy
(check size) filtering:
j_new = [J[i] for i, a in enumerate(CB) if np.array(a).size != 0]
[1, 35]