6

I want to pick out some items in one rectangular box with axis limits of (xmin, xmax, ymin, ymax, zmin, zmax). So i use the following conditions,

if not ((xi >= xmin and xi <= xmax) and (yi >= ymin and yi <= ymax) and (zi >= zmin and zi <= zmax)):
    expression 

But I think python has some concise way to express it. Does anyone can tell me?

Gao
  • 103
  • 4

2 Answers2

14

Typical case for operator chaining:

if not (xmin <= xi <= xmax and ymin <= yi <= ymax and zmin <= zi <= zmax):

Not only it simplifies the comparisons, allowing to remove parentheses, while retaining readability, but also the center argument is only evaluated once , which is particularly interesting when comparing against the result of a function:

if xmin <= func(z) <= xmax:

(so it's not equivalent to 2 comparisons if func has a side effect)

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
1

If you really want to start cooking with gas, create a class library for handling 3D points (e.g. by extending this one to include the Z coordinate: Making a Point Class in Python).

You could then encapsulate the above solution into a method of the class, as:

def isInBox(self, p1, p2):
    return (p1.X <= self.X <= p2.X and p1.Y <= self.Y <= p2.Y and p1.Z <= self.Z <= p2.Z)
AltShift
  • 336
  • 3
  • 18