IF statement with 2 variables and 4 conditions
我有两个变量,比如x和y,我需要检查其中哪个是
1 2 3 4 5 6 7 8 9 10 | 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 |
有没有更好的方法?我在找一个较短的
保持您使用的顺序:
1 2 3 4 5 6 7 8 | 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 |
修改顺序以减少布尔值计算:
1 2 3 4 5 6 7 8 | 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个条件,因此这两个选项的顺序无关紧要。例如,上面的第一个代码认为
假设您需要将所有4个案例单独涵盖:
1 2 3 4 5 6 7 8 | if not x and not y: # code here (both are none or 0) elif not x # code here (x is none or 0) elif not y # code here (y is none or 0) else #code here (both x and y have values) |
这是处理它的最短方法,但不仅检查无/空值。
如果你有两个乳房,有四种不同的可能性:00 01 10和11。如果在每种情况下都会发生明显不同的事情,那么就没有真正的事情可以减少测试的数量。唯一的方法是引入三个if语句(如1&1、0&1、1&0)和一个默认值(将捕获00),从而节省一个比较。在绝大多数情况下,这可能是不相关的,甚至可能是编译器或解释器做的任何事情。至少我被最近看到的海湾合作委员会的一些魔术表演搞糊涂了。
您可以从使用
1 2 3 4 5 6 7 8 | if x is None and y is None: # code here elif x is not None and y is not None: # code here elif x is None: # code here if y is None: # code here` |
如果每个可能的
像这样:
1 2 3 4 5 6 7 8 9 10 | 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 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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) |
输出:
1 | 100 |
下面的逻辑应该针对所有组合运行。用你的语言写
1 2 3 4 5 6 7 8 9 10 11 12 13 | if (x is not null and y is not null){ //code here } else if(x is null and y is not null){ //code here } else if(x is not null and y is null){ //code here } else { //Code here } |
相同的C代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | int main() { int x,y; printf("Enetr Two Number"); scanf("%d%d",&x,&y); if(x!=NULL && y!=NULL) printf("X and Y are not null"); else if(x==NULL && y!=NULL) printf("X is null and Y is not null"); else if(x!=NULL && y==NULL) printf("X is not null and Y is null"); else { printf("The value of x and y are null"); } } |