加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 11:51:05 所属栏目:Python 来源:网络整理
导读:所以我想写这个: 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: 我该如何以正确的方式写出来? 解决方法 或者是一个布尔运算符.它在左参数上调用bool并查看结果是否为True,如果是,则返回左参数,否
所以我想写这个:

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:

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

解决方法

或者是一个布尔运算符.它在左参数上调用bool并查看结果是否为True,如果是,则返回左参数,否则返回正确的参数,因此不能执行x%(1或2或3),因为它的计算结果为x %1从1或2或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来减少它们.

我们认为任何([a,b,c,d])等于a或b或c或d,而所有([a,d])等同于a和b以及c和d除外他们总是回归真或假.

例如:

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

等价(从0开始,如果唯一的错误数字== 0相当于没有):

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

等价的:

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

请记住(de Morgan法:不是或不是b ==不是(a和b)):

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

请注意,使用生成器表达式会导致任何和所有短路,因此不会评估所有条件.看看之间的区别:

>>> 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>",in <listcomp>
ZeroDivisionError: division by zero
>>> 1/0 or 1
Traceback (most recent call last):
  File "<stdin>",in <module>
ZeroDivisionError: division by zero

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读