Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplification of if multiple conditions in python

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?

like image 879
Gao Avatar asked Dec 12 '18 21:12

Gao


People also ask

How do you simplify if else in Python?

Use a dictionary to simplify a long if statement Since the dictionary maps strings to functions, the operation variable would now contain the function we want to run. All that's left is to run operation(numbers) to get our result. If the user entered 'add' , then operation will be the sum function.

Can you have 3 conditions in an if statement in Python?

YOU ARE NOT ALLOWED. BYE ! Not just two conditions we can check more than that by using 'and' and 'or'.

Can you have 2 if statements in Python?

We can have a if...elif...else statement inside another if...elif...else statement. This is called nesting in computer programming. Any number of these statements can be nested inside one another.


1 Answers

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)

like image 168
Jean-François Fabre Avatar answered Sep 30 '22 19:09

Jean-François Fabre