将布尔元组用于if语句

时间:2019-04-07 13:02:57

标签: python python-3.x if-statement tuples

我想知道在if语句中使用元组而不是单独的表达式是否是一个好习惯。

is_dog = True
is_brown = False

我想这样做:

if (is_dog, is_brown):
    do_something()

而不是这样:

if is_dog or is_brown:
    do_something()

在这种情况下,最佳做法是什么? 谢谢

2 个答案:

答案 0 :(得分:4)

这里发生了一些事情:

您正在使用元组作为if的分支值。谓词的真实性仅表示谓词是否为空,而其内容无关:

assert bool(tuple()) is False
assert bool((False, )) is True

第二,如果您事先知道元组中的项数,通常使用orand更具可读性,就像您提到的那样:

if is_dog or is_cat:
    do_something()

最后,您可以对任意数量的值使用any

values = [is_dog, is_cat, ... more]
if any(values):
    do_something()

答案 1 :(得分:3)

这是不是的好习惯,看看是否其中一个布尔值是True

if (False,False):
    print("it does not do what you think it does")

输出:

it does not do what you think it does

请参见python truth value testing:任何非空元组都是True-您的

正确的方法是:

if a or b:   
    pass

对于倍数,您可以使用any()

if any(x for x in (False, True)):
    pass   # will enter here if any part of the tuple is True
else:
    pass   # will enter here if no part of the tuple is True
相关问题