简体   繁体   English

检查python中的多个条件

[英]checking multiple conditions in python

I have below code: 我有下面的代码:

a = 1
b = 2
c = 3
d = 4
e = 5
if ((a == 1 and
     b == 2 and
     c == 4) or
     (d == 4  and e == 5)):
    print "Yeah, Working"
else:
    print "ooops"

Can be achieved same code easy and best way? 可以实现相同的代码简单和最好的方法吗?

If you want to if condition to be clearer or better looking, you can do it like this: 如果你想要条件更清晰或更好看,你可以这样做:

a = 1
b = 2
c = 3
d = 4
e = 5
if (a, b, c) == (1, 2, 4) or (d, e) == (4, 5):
    print "Yeah, Working"
else:
    print "ooops"

It's a very personal answer, but I like to initalize some boolean before the if statement. 这是一个非常个人化的答案,但我喜欢在if语句之前初始化一些布尔值。 I find it more readable (because you can give some meaningful name to your variable), and I'm pretty sure the compiler can easily optimize it. 我发现它更具可读性(因为你可以为你的变量赋予一些有意义的名字),而且我很确定编译器可以轻松地对它进行优化。

cond1 = a == 1 and b == 2 and c == 4
cond2 = d == 4 and e == 5
if cond1 or cond2:
    print("Yeah, working")
else:
    print("ooops")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM