如何简化if语句中的多个或条件?

FCD*_*FCD 3 python if-statement python-3.x

所以我想写这个:

if x % 2 == 0 or x % 3 == 0 or x % 5 == 0 or x % 7 == 0:
Run Code Online (Sandbox Code Playgroud)

但是这样:

if x % (2 or 3 or 5 or 7) == 0:
Run Code Online (Sandbox Code Playgroud)

我该如何以正确的方式写出来?

Bak*_*riu 7

or是一个布尔运算符.它调用bool了左边参数,看看结果是True,如果是则返回左参数,否则返回正确的参数,所以你不能这样做x % (1 or 2 or 3),因为这个计算结果只是x % 1因为1 or 2 or 3 == 1:

>>> True or False
True
>>> False or True
True
>>> False or False
False
>>> 1 or False   # all numbers != 0 are "true"
1
>>> bool(1)
True
>>> 1 or 2 or 3   #(1 or 2) or 3 == 1 or 3 == 1
1
Run Code Online (Sandbox Code Playgroud)

每当您有多个条件时,您可以尝试使用any或减少它们all.

我们有any([a,b,c,d])相当于a or b or c or dwhile all([a,b,c,d])等同于a and b and c and d 除了它们总是返回TrueFalse.

例如:

if any(x%i == 0 for i in (2,3,5,7)):
Run Code Online (Sandbox Code Playgroud)

等价(因为0如果唯一的假数== 0相当于not):

if any(not x%i for i in (2,3,5,7)):
Run Code Online (Sandbox Code Playgroud)

等价的:

if not all(x%i for i in (2,3,5,7))
Run Code Online (Sandbox Code Playgroud)

请记住(de Morgan law :) not a or not b == not (a and b):

any(not p for p in some_list) == not all(p for p in some_list)
Run Code Online (Sandbox Code Playgroud)

注意,使用一个发电机表达使其anyall短路所以不是所有的条件进行评估.看看之间的区别:

>>> any(1/x for x in (1,0))
True
>>> 1 or 1/0
1
Run Code Online (Sandbox Code Playgroud)

和:

>>> any([1/x for x in (1,0)])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
ZeroDivisionError: division by zero
>>> 1/0 or 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
Run Code Online (Sandbox Code Playgroud)

在最后一个例子中,调用之前1/0进行评估.any