简体   繁体   中英

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

any should be after the brackets, and y should be a numpy array.

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.

it's like doing true/false < -10

The correct use of np.any() would be as follows:

(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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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