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

3

所以我想写这个:

if x % 2 == 0 or x % 3 == 0 or x % 5 == 0 or x % 7 == 0:

但是这样做:

if x % (2 or 3 or 5 or 7) == 0:

我应该如何以正确的方式编写它?


1
如果任何一个x除以[2, 3, 5, 7]中的数字余数不为零: 现在谁能帮我找到重复目标? - Remi Guan
3
实际上:if any(not x%i for i in (2,3,5,7)) 或者 if not all(x%i for i in (2,3,5,7)) - Bakuriu
1
@Bakuriu: 啊,对了。或者像 OP 的代码一样,只需写成 if any(x % i == 0 for i in [2, 3, 5, 7]): - Remi Guan
我对你们如此迅速地回答我的问题感到惊讶。谢谢你们! - FCD
1
我已经编辑了标题,以便使这个问题可以被搜索到。我知道这个问题已经被问了很多次,但是尝试像“python multiple or”等显而易见的方法并没有得到任何好的结果。 - Bakuriu
1个回答

8

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

每当您有多个条件时,可以尝试使用anyall来简化它们。
我们有any([a,b,c,d])等同于a or b or c or d,而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)):

同样地(因为0是唯一的假数字,== 0等价于not):

if any(not x%i for i in (2,3,5,7)):

同样地:

if not all(x%i for i in (2,3,5,7))

请记住(de Morgan定律:非a或非b等于非(a且b)):

any(not p for p in some_list) == not all(p for p in some_list)

请注意,使用生成器表达式可以使anyall短路,因此不会评估所有条件。请参见以下示例的差异:
>>> any(1/x for x in (1,0))
True
>>> 1 or 1/0
1

和:

>>> 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

在上一个例子中,在调用any之前,1/0被计算出来了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接