import numpy as np
a = np.eye(2)
b = np.array([1,1],[0,1])
my_list = [a, b]
a in my_list
returns true
, but b in my_list
returns "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()". I can get around this by converting the arrays to strings or lists first, but is there a nicer (more Pythonic) way of doing it?
The problem is that in numpy the ==
operator returns an array:
>>> a == b
array([[ True, False],
[ True, True]], dtype=bool)
You use .array_equal()
to compare arrays to a pure boolean value.
>>> any(np.array_equal(a, x) for x in my_list)
True
>>> any(np.array_equal(b, x) for x in my_list)
True
>>> any(np.array_equal(np.array([a, a]), x) for x in my_list)
False
>>> any(np.array_equal(np.array([[0,0],[0,0]]), x) for x in my_list)
False
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