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])]]
Asked By: rajunarlikar123

||

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] = [] 
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.