A simpler way to write a conditional statement

Is there a nicer way to write this if statement:

if not (self.is_legal(l) or self.is_legal(u) or self.is_legal(r) or self.is_legal(d)):

I tried this, but it did not work.

if not self.is_legal(l or r or d or u):

Or maybe the first of them is the most beautiful?

+4
source share
3 answers

You can use anyand a generator expression :

if not any(self.is_legal(x) for x in (l, u, r, d)):

Or, if you prefer allinstead any:

if all(not self.is_legal(x) for x in (l, u, r, d)):

The first solution seems a little better though.


As for why your tried solution didn't work, the operator orin Python doesn't behave the way you think. From docs :

x or y x; x , ; y, .

, self.is_legal(l or r or d or u) self.is_legal, .

+12

:

if False in (self.is_legal(l), self.is_legal(u), self.is_legal(r), self.is_legal(d)):

if {False} <= {self.is_legal(l), self.is_legal(u), self.is_legal(r)}:

:

if {False} <= {self.is_legal(var) for var in (l, u, r, d)}: 

, - :

if [var for var in (l, u, r, d) if self.is_legal(var) is False]:

, , "".

0

The empty list in Python is false.

You can create an empty list with understanding and conditional:

>>> def is_legal(x):
...    return x>5
... 
>>> bool([x for x in (1,2,3,4) if is_legal(x)])
False
>>> bool([x for x in (1,2,3,4,6) if is_legal(x)])
True
0
source

All Articles