Reputation: 103
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?
Upvotes: 6
Views: 192
Reputation: 346
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)
Upvotes: 1
Reputation: 140148
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)
Upvotes: 14