IF语句有2个变量和4个条件
我有2个变量,例如x和y,我需要检查其中哪些是None
if x is None and y is None:
# code here
else:
if x is not None and y is not None:
# code here
else:
if x is None:
# code here
if y is None:
# code here
有没有更好的方法来做到这一点?
我正在寻找一个更短的IF ELSE
结构。
保持您使用的订单:
if x is None and y is None:
# code here for x = None = y
elif x is not None and y is not None:
# code here for x != None != y
elif x is None:
# code here for x = None != y
else:
# code here for x != None = y
修改顺序以减少布尔评估:
if x is None and y is None:
# code here for x = None = y
elif x is None:
# code here for x = None != y
elif y is None:
# code here for x != None = y
else:
# code here for x != None != y
在4种情况下,您应该考虑哪些选项具有更高的概率,哪些具有更高的选项,并保留前两个选项,因为这样会减少执行期间检查的条件数量。 最后两个选项将执行3个条件,所以这两个顺序无关紧要。 例如上面的第一个代码认为prob(x=None & y=None) > prob(x!=None & y!=None) > prob(x=None & y!=None) ~ prob(x!=None & y=None)
,而第二个认为prob(x=None & y=None) > prob(x=None & y!=None) > prob(x!=None & y=None) ~ prob(x!=None & y!=None)
def func1(a):
print a
def func2(a):
print a
def func3(a):
print a
def func4(a):
print a
options = {(1, 1): func1,
(1, 0): func2,
(0, 1): func3,
(0, 0): func4,}
options[(True, True)](100)
输出:
100
如果你需要4种不同的路径来表示x
和y
的可能组合,你不能真正简化它。 也就是说,我将检查其中一个变量(例如,先检查x is None
,然后检查y is None
。
像这样的东西:
if x is None:
if y is None:
# x is None, y is None
else:
# x is None, y is not None
else:
if y is None:
# x is not None, y is None
else:
# x is not None, y is not None
链接地址: http://www.djcxy.com/p/76639.html