shorthand for and/or in python if 语句

shorthand for and/or in python if statements

如果您对多个值进行相同的比较,是否有 shorthand 方法在 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 用于 and:

# 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:
    ...

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


对于or,您可以使用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):
    ...

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

如果值是可散列的:

if set((a, b, c)) == {1}:
    # All are 1.

或者如果这3个值都是非负整数,将它们全部相乘,看结果是否为1?

if a * b * c == 1:
    # All are 1.

通用答案是 all(..),如 mgilson 的答案。