英文:
List elements less than tolerance in Python
问题
if (Test[i][j]<tol):
英文:
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])]]
答案1
得分: 2
# 列表推导式怎么样?
out = [[[] if (a < tol).all() else a for a in l] for l in Test]
# 修复你的代码:
for i in range(len(Test)):
for j in range(len(Test[i])):
if Test[i][j] < tol:
Test[i][j] = []
英文:
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] = []
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论