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?

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

7 Comments

@Gao If their answer satisfies your question, please mark it as such with the green checkmark.
@TheIncorrigible1 thanks. Was trying to get an internal bookmark on that page :)
Just wondering how that is valid. xmin <= xi returns True, which is evaluated as 1 and then it shouldn't make sense, but surprisingly, it works perfectly fine
@Ayxan Comparison operators don't associate in this case; x <= 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.
|
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)

1 Comment

Yes. I understand your idea. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.