[英]How to simplify multiple or conditions in an 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
並查看結果是否為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 d
而all([a,b,c,d])
等同於a and b and c and d
除外他們總是回歸True
或False
。
例如:
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法: 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)
請注意,使用生成器表達式會any
和all
短路,因此不會評估所有條件。 看看之間的區別:
>>> 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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.