a < b < c
is an chained expression in Python, and it looks like it works on objects with appropriate comparison operators defined, but it doesn't work on numpy arrays. Why?
import numpy as np
class ContrarianContainer(object):
def __init__(self, x):
self.x = x
def __le__(self, y):
return not self.x <= y
def __lt__(self, y):
return not self.x < y
def __ge__(self, y):
return not self.x >= y
def __gt__(self, y):
return not self.x > y
def __eq__(self, y):
return not self.x == y
def __ne__(self, y):
return not self.x != y
numlist = np.array([1,2,3,4])
for n in numlist:
print 0 < n < 3.5
for n in numlist:
print 0 > ContrarianContainer(n) > 3.5
print 0 < numlist < 3.5
this prints:
True
True
True
False
True
True
True
False
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-187-277da7750148> in <module>()
4 for n in numlist:
5 print 0 < n < 3.5
----> 6 print 0 < numlist < 3.5
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
0 < numlist < 3.5
Is equivalent to:
(0 < numlist) and (numlist < 3.5)
except that numlist
is only evaluated once.
The implicit and
between the two results is causing the error
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