Skip to main content
 首页 » 编程设计

python之和/或在 python if 语句中的简写

2025年05月04日24qlqwjy

如果您对多个值进行相同的比较,是否有一种在 if 语句中编写比较的简写方法。只是好奇这样的事情是否可能。感谢您的帮助!

a =1 
b =1 
c =1 
 
if a == 1 and b ==1 and c == 1: 
    print('yes') 
 
# It would be nice if you could do this or something like it. 
if a,b,c == 1: 
    print('this would be easier') 

请您参考如下方法:

和可以使用all:

# same as: 
# if a == 1 and b == 1 and c == 1: 
if all(x == 1 for x in (a, b, c)): 
    ... 

或者您可以使用运算符链接:

if a == b == c == 1: 
    ... 

但我在实际代码中看不到这一点。


对于或,你可以使用any:

# same as: 
# if a == 1 or b == 1 or c == 1: 
if any(x == 1 for x in (a, b, c)): 
    ... 

据我所知,尽管您可以使用in,但没有运算符链接技巧:

if 1 in (a, b, c): 
    ... 

这确实有一些性能影响(即它为比较创建了一个新元组)。通常这是非常便宜的,但在最紧密的循环中不会引起注意。