List elements less than tolerance in Python
Question:
I have a list Test
containing numpy arrays. I want to see if each array element is less than the tol
value. If it is less, it should return empty list. But I am getting an error. I present the expected output.
import numpy as np
tol=1e-12
Test=[[np.array([9.75016872e-15])], [np.array([9.75016872e-15]), np.array([0.00019793]), np.array([0.0001007])]]
for i in range(0,len(Test)):
for j in range(0,len(Test[i])):
if (Test[j][i]<tol):
Test[j][i]=[]
else:
Test=Test[j][i]
print(Test)
The error is
in <module>
if (CB[j][i]<tol):
IndexError: list index out of range
The expected output is
[[[]], [[], array([0.00019793]), array([0.0001007])]]
Answers:
What about a list comprehension?
out = [[[] if (a<tol).all() else a for a in l] for l in Test]
# [[[]], [[], array([0.00019793]), array([0.0001007])]]
Fix of your code:
for i in range(len(Test)):
for j in range(len(Test[i])):
if Test[i][j] < tol:
Test[i][j] = []
I have a list Test
containing numpy arrays. I want to see if each array element is less than the tol
value. If it is less, it should return empty list. But I am getting an error. I present the expected output.
import numpy as np
tol=1e-12
Test=[[np.array([9.75016872e-15])], [np.array([9.75016872e-15]), np.array([0.00019793]), np.array([0.0001007])]]
for i in range(0,len(Test)):
for j in range(0,len(Test[i])):
if (Test[j][i]<tol):
Test[j][i]=[]
else:
Test=Test[j][i]
print(Test)
The error is
in <module>
if (CB[j][i]<tol):
IndexError: list index out of range
The expected output is
[[[]], [[], array([0.00019793]), array([0.0001007])]]
What about a list comprehension?
out = [[[] if (a<tol).all() else a for a in l] for l in Test]
# [[[]], [[], array([0.00019793]), array([0.0001007])]]
Fix of your code:
for i in range(len(Test)):
for j in range(len(Test[i])):
if Test[i][j] < tol:
Test[i][j] = []