Home > Net >  Test if any values in list are in other list
Test if any values in list are in other list

Time:10-16

I have a List, L, and some Values, V. If none of them are in the List it passes the condition. As for the other side, if one of them it's in the list it passes the other condition.

The code should be something like this

If "none elements of" V in L:
    print("OK")
If "one element of" V in L:
    print("Not OK")

For example I have the following list:

L= [(3, 0), (3, 2), (3, 4)]

And I want to check with the values in the array v, for example:

V = [0,1]

With this V and this L it should print "Not OK" because 0 is in the list. If V was something like V = [1,5] it should print "OK" because none of the elements of V are in the list L

I have tried the any(x in V for x in L), the [(x in L) for x in V] and the [x for x in V if x in L] and can´t make any work (it always gives me "Not OK").

Also I would like to said that I would be working with big arrays (Len(V) and Len(L) while be very big) so I would also like the most optmized way to do it

CodePudding user response:

You can use np.isin(). This function will return True for any value of V that is in L. Then sum the result as follows:

import numpy as np

if np.isin(L, V).sum()>0:
    print ('Not OK')
else:
    print('OK')

CodePudding user response:

You can do this with flatten the list of tuples and check with members in the method.

if any(item in [j for i in L for j in i] for item in V):
    print ('Not OK')
else:
    print('OK')
  • Related