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

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

List elements less than tolerance in Python

问题

  1. 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.

  1. import numpy as np
  2. tol=1e-12
  3. Test=[[np.array([9.75016872e-15])], [np.array([9.75016872e-15]), np.array([0.00019793]), np.array([0.0001007])]]
  4. for i in range(0,len(Test)):
  5. for j in range(0,len(Test[i])):
  6. if (Test[j][i]&lt;tol):
  7. Test[j][i]=[]
  8. else:
  9. Test=Test[j][i]
  10. print(Test)

The error is

  1. in &lt;module&gt;
  2. if (CB[j][i]&lt;tol):
  3. IndexError: list index out of range

The expected output is

  1. [[[]], [[], array([0.00019793]), array([0.0001007])]]

答案1

得分: 2

  1. # 列表推导式怎么样?
  2. out = [[[] if (a < tol).all() else a for a in l] for l in Test]
  3. # 修复你的代码:
  4. for i in range(len(Test)):
  5. for j in range(len(Test[i])):
  6. if Test[i][j] < tol:
  7. Test[i][j] = []
英文:

What about a list comprehension?

  1. out = [[[] if (a&lt;tol).all() else a for a in l] for l in Test]
  2. # [[[]], [[], array([0.00019793]), array([0.0001007])]]

Fix of your code:

  1. for i in range(len(Test)):
  2. for j in range(len(Test[i])):
  3. if Test[i][j] &lt; tol:
  4. 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:

确定