Reputation: 1168
I have a list of 3x3 arrays l
and I want to check if a different single 3x3 array a
is in the list. I tried like this:
a in l
but it couldn't be executed beacuse of the following error:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
I cannot grasp why such a comparison would be ambiguous (the intention is clear), but anyway, is there a way to solve my problem?
Upvotes: 4
Views: 16386
Reputation: 126
It worked well on my side when I tried it, but I found some returns that were inaccurate.
a= np.ones((3,3))
b= np.ones((3,3))
a in b
#output True
b in a
#output True
but when I changed the length of arrays in one, and not the other some discrepancies came out.
a= np.ones((3,3))
b= np.ones((4,3))
a in b
#Output- False #this was the same for the reverse
np.any(a ==b)
#Output False #This also threw up a depreciation warning forelementwise == comparison
np.any(a[0] == b[0])
#OutPut True
for i in range(len(a)):
if a[i] in b[i]:
print('yes')
#OutPut yes yes yes
seems it doesn't like comparing an array of array's as much as it likes doing it one by one.
Upvotes: 0
Reputation: 2543
Numpy is confused there on what you want to do. Do you want to know if a
is equivalent to any element of l
or if a
is an element of l
.
a = np.ones((3,3))
b = np.ones((3,3))
l = [b]
b in l
>>True
a in l
>>
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-17-cf48b78477bf> in <module>()
----> 1 a in l
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
An alternative for this, if you want to know if a
is in l
is to use id()
function.
so
ids = map(id, l)
id(a) in ids
>> False
id(b) in ids
>>True
Upvotes: 3
Reputation: 2908
a.all()
and a.any()
could only be done using numpy. Now numpy needs to know if you'd consider it a match if -
any
- any of the elements matchall
- all of the elements matchIts not about intentions. Its about providing functions that the community would find helpful. So in your case you'd probably use a.all
This SO post should clear it up for you. I essentially provided the gist above.
Upvotes: 2