在一个“if"语句中评估多个变量? [英] Evaluate multiple variables in one 'if' statement?
问题描述
假设我有一堆变量,它们要么是 True
,要么是 False
.我想在一个 if 语句中评估一组这些变量,看看它们是否都是 False
像这样:
Say I have a bunch of variables that are either True
or False
. I want to evaluate a set of these variables in one if statement to see if they are all False
like so:
if var1, var2, var3, var4 == False:
# do stuff
除非那不起作用.我知道我可以做到这一点:
Except that doesn't work. I know I can do this:
if var1 == False and var2 == False and var3 == False and var4 == False:
# do stuff
但这相当难看 - 特别是如果这些 if 语句将在我的代码中出现很多.有没有什么方法可以用更简洁的语法(如第一个示例)进行此评估?
But that's fairly ugly - especially if these if statements are going to occur a lot in my code. Is there any sort of way I can do this evaluation with a cleaner syntax (like the first example)?
推荐答案
你应该永远不要使用 == True
(或 == False
) 测试布尔变量.相反,要么写:
You should never test a boolean variable with == True
(or == False
). Instead, either write:
if not (var1 or var2 or var3 or var4):
if not any((var1, var2, var3, var4)):
或使用 Python 的传递比较:
or use Python's transitive comparisons:
if var1 == var2 == var3 == var4 == False:
这篇关于在一个“if"语句中评估多个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!