在Python中,筛选小于给定公差的列表元素。

huangapple go评论67阅读模式
英文:

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]&lt;tol): 
            Test[j][i]=[] 
        else: 
            Test=Test[j][i]
print(Test)

The error is

in &lt;module&gt;
    if (CB[j][i]&lt;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&lt;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] &lt; tol:
            Test[i][j] = [] 

huangapple
  • 本文由 发表于 2023年2月14日 00:42:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75438803.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定