如何简化if语句中的多个或条件? [英] How to simplify multiple or conditions in an if statement?

查看:1319
本文介绍了如何简化if语句中的多个或条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想写这个:

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:

我应该如何正确地写出来?

How should I write it in a proper way?

推荐答案

是一个布尔运算符。它在左参数上调用 bool ,看看结果是否为 True ,如果是,则返回左参数,否则它返回正确的参数,所以你不能做 x%(1或2或3)因为这只评估 x%1 因为 1或2或3 == 1

or is a boolean operator. It calls bool over the left argument and see if the result is True and if it is it returns the left argument, otherwise it returns the right argument, so you cannot do x % (1 or 2 or 3) because this evaluates to just x % 1 since 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

每当有多个条件时,您可以尝试使用 <$来减少它们c $ c>任何 全部

Whenever you have multiple conditions you can try to reduce them using any or all.

我们有 any([a,b,c, d])相当于 a或b或c或d ,而全部([a,b,c,d ])相当于 a和b和c和d 以外它们总是返回 True False

We have that any([a,b,c,d]) is equivalent to a or b or c or d while all([a,b,c,d]) is equivalent to a and b and c and d except that they always return True or False.

例如:

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

等价(因为 0 如果唯一的错误号码 == 0 相当于而不是):

Equivalently (since 0 if the only false number the == 0 is equivalent to 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法律:不是或不是b ==不是(a和b)):

Keep in mind that (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)

请注意,使用生成器表达式会使任何所有短路因此并非所有条件都被评估。请查看以下内容之间的区别:

Note that using a generator expression makes any and all short-circuit so not all conditions are evaluated. See the difference between:

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

在上一个例子中 1在调用任何之前评估

In the last example the 1/0 is evaluated before calling any.

这篇关于如何简化if语句中的多个或条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆