python - 如何简化 if 语句中的多个 or 条件?

标签 python python-3.x if-statement

所以我想这样写:

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:

应该怎么写才合适呢?

最佳答案

or 是 bool 运算符。它在左侧参数上调用 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

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

我们有 any([a,b,c,d]) 等价于 a or b or c or dall([a ,b,c,d]) 等同于 a and b and c and d except 它们总是返回 True错误

例如:

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

请记住(德摩根定律: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)

请注意,使用生成器表达式会使 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

在最后一个例子中,1/0 调用 any 之前被求值。

关于python - 如何简化 if 语句中的多个 or 条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36449872/

相关文章:

python - 使用聚合值、多列解析 CSV 文件

python - 将Python字典中的元素移动到另一个索引

python - 为什么 MongoEngine/pymongo 仅在第一次尝试访问对象时出错

javascript - 当等效的 if 语句起作用时,switch 语句不起作用

python - 加载预先计算的向量 Gensim

python - 在使用子进程的脚本上使用 Py2App 后收到启动错误

python - 从列表中创建一个新列表但没有重复项?

performance - 我可以使这个 if else 语句更有效率吗

python - 断言错误: View function mapping is overwriting an existing endpoint function

python - 如何有效地定位句子中特定的单词序列