在一个'if'语句中评估多个变量? [英] Evaluate multiple variables in one 'if' statement?

查看:106
本文介绍了在一个'if'语句中评估多个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一堆变量 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)?

推荐答案

你应该< a href =https://softwareengineering.stackexchange.com/questions/12807/make-a-big-deal-out-of-true>永远不要用 == 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):

或使用 任何 (在相关问题中,其堂兄 全部 ):

or use any (and in related problems its cousin all):

if not any((var1, var2, var3, var4)):

或使用Python的传递性比较

or use Python's transitive comparisons:

if var1 == var2 == var3 == var4 == False:

这篇关于在一个'if'语句中评估多个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆