简体   繁体   English

Python中列表的条件检查

[英]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")

I want to check whether in a list any value below or above a particular value exists or not.我想检查列表中是否存在低于或高于特定值的任何值。 So, I proceed with np.any(), code is getting compiled but not working as wished, I mean not printing back "yes".所以,我继续使用 np.any(),代码正在编译但没有按预期工作,我的意思是不打印回“是”。

any should be after the brackets, and y should be a numpy array. 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() returns a bool and you cannot compare it with an int. np.any()返回一个 bool 并且您不能将它与 int 进行比较。

it's like doing true/false < -10这就像做true/false < -10

The correct use of np.any() would be as follows: 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')

Your Output你的输出

yes there is -11.23 less than -10是的,-11.23 小于 -10

This should do the job这应该可以胜任

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")

Other option will be to not use numpy module, and just to scan the array elements one by one.另一种选择是不使用 numpy 模块,而只是一个一个地扫描数组元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM