What's an easiest way to check whether or not 2 arrays have at least one element in common? Using numpy is possible, but not necessarily.
The code I've found so far only checks for the concrete common elements. Whereas I need only to check True or False condition.
Assuming the input arrays to be A
and B
, you can use np.in1d
with np.any
, like so -
import numpy as np
np.in1d(A,B).any()
You can also use NumPy's broadcasting capability
, like so -
(A.ravel()[:,None] == B.ravel()).any()
You can use any
:
any(x in set(b) for x in a)
This is short to write but, as Jon has rightly pointed out it will create a new set(b)
for each element at a
, the following lines would avoid that:
sb = set(b)
any(x in sb for x in a)
Performance will improve if b
is the largest array (compared to a
):
(smaller,bigger) = sorted([a,b], key=len)
sbigger = set(bigger)
any(x in sbigger for x in smaller)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With