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?
2 Answers 2
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)
7 Comments
xmin <= xi returns True, which is evaluated as 1 and then it shouldn't make sense, but surprisingly, it works perfectly finex <= y <= z is evaluated like x <= y and y <= z (but with y evaluated only once). It doesn't simply evaluate x <= y and then compare the result to z.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)