[Numpy-discussion] multi-comparison expressions

Nadav Horesh nadavh@visionsense....
Mon Oct 6 14:49:20 CDT 2008


a < b < c 

is equivalent to:

(a < b) and (b < c)

If you wand an element-wise operation you have to use the & operator, so the expression is:

(a > 2) & (a < 5)

   Nadav


-----הודעה מקורית-----
מאת: numpy-discussion-bounces@scipy.org בשם John
נשלח: ב 06-אוקטובר-08 21:32
אל: numpy-discussion@scipy.org
נושא: [Numpy-discussion] multi-comparison expressions
 
hi,

why does the ValueError appear below, and how can i make that 2<a<5 
expression work when a is an array?

thanks.

 >>> from numpy import reshape,arange
 >>> a=reshape(arange(9),(3,3))
 >>> a
array([[0, 1, 2],
      [3, 4, 5],
      [6, 7, 8]])
 >>> 2<a
array([[False, False, False],
      [ True,  True,  True],
      [ True,  True,  True]], dtype=bool)
 >>> a<5
array([[ True,  True,  True],
      [ True,  True, False],
      [False, False, False]], dtype=bool)
 >>> 2<a<5
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is 
ambiguous. Use a.any() or a.all()

nor does it work with constant arrays:

 >>> from numpy import zeros
 >>> twos=zeros(a.shape)+2
 >>> fives=zeros(a.shape)+5
 >>> twos<a
array([[False, False, False],
      [ True,  True,  True],
      [ True,  True,  True]], dtype=bool)
 >>> a<fives
array([[ True,  True,  True],
      [ True,  True, False],
      [False, False, False]], dtype=bool)
 >>> twos<a<fives
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is 
ambiguous. Use a.any() or a.all()

but it works with builtin numbers:

 >>> b=3
 >>> 2<b<5
True


_______________________________________________
Numpy-discussion mailing list
Numpy-discussion@scipy.org
http://projects.scipy.org/mailman/listinfo/numpy-discussion

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/ms-tnef
Size: 3376 bytes
Desc: not available
Url : http://projects.scipy.org/pipermail/numpy-discussion/attachments/20081006/9533aac9/attachment.bin 


More information about the Numpy-discussion mailing list