[英]conditional checking of a list in Python
import numpy as np
y = [1.25, 2.59, -4.87, 6.82, -7.98, -11.23]
if(np.any(y) < -10):
print("yes")
我想检查列表中是否存在低于或高于特定值的任何值。 所以,我继续使用 np.any(),代码正在编译但没有按预期工作,我的意思是不打印回“是”。
any
应该在括号之后, y
应该是一个numpy
数组。
import numpy as np
y = np.array([1.25, 2.59, -4.87, 6.82, -7.98, -11.23])
if (y < -10).any():
print("yes")
np.any()
返回一个 bool 并且您不能将它与 int 进行比较。
这就像做true/false < -10
np.any() 的正确使用如下:
(y < -10).any()
y = [1.25, 2.59, -4.87, 6.82, -7.98, -11.23]
for value in y:
if value < -10:
print(f'yes there is {value} less than -10')
你的输出
这应该可以胜任
import numpy as np
y1 = np.array([1.25, 2.59, -4.87, 6.82, -7.98, -11.23])
y2 = np.array([1.25, 2.59, 4.87, 6.82, 7.98, 11.23])
if(np.any(y1 < -10)):
print("yes y1")
else:
print("no y1")
if(np.any(y2 < -10)):
print("yes y2")
else:
print("no y2")
另一种选择是不使用 numpy 模块,而只是一个一个地扫描数组元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.