Numpy: Need A Hand In Understanding What Happens With The "in" Operator
Solution 1:
Python makes the choice that bool([False,True])
is True
because (it says) any non-empy list has boolean value True.
Numpy makes the choice that bool(np.array([False, True]))
should raise a ValueError. Numpy was designed from the point of view that some users may want to know if any of the elements in the array are True, while others may want to know if all the elements in the array are True. Since the users may have conflicting desires, NumPy refuses to guess. It raises a ValueError and suggests using np.any
or np.all
(though if one wishes to replicate Python-like behavior, you'd use len
).
When you evaluate c in l
, Python compares c
with each element in l
starting with a
. It evaluates bool(c==a)
. We get bool(np.array([True True]))
, which raises a ValueError (for the reason described above).
Since numpy refuses to guess, you have to be specific. I suggest:
import numpy as np
a=np.array((2,1))
b=np.array((3,3))
c=np.array((2,1))
l=[a,b]
print(any(np.all(c==elt) for elt in l))
# True
Post a Comment for "Numpy: Need A Hand In Understanding What Happens With The "in" Operator"