简体   繁体   English

用Python编写级联if语句的方法

[英]Pythonic way to write cascading if statements

Is there a more Pythonic way to write the following function? 有没有更多的Python方式可以编写以下函数?

def foo():
    flag = False
    if condition1:
        if condition2:
            flag = True
    return flag

Here you go: 干得好:

def foo():
    return bool(condition1 and condition2)

You could simplify it like below: 您可以像下面这样简化它:

def foo:
   return condition1 and condition2

Note that the variable flag is not being used anywhere, and so it is perfectly fine to remove it in this case. 请注意,变量标记未在任何地方使用,因此在这种情况下将其删除是完全可以的。

If you are looking for the function to return exactly one of True or False then you can simplify like this: 如果您正在寻找要返回TrueFalse之一的函数,则可以这样简化:

def foo():
    return bool(condition1 and condition2)

This replicates exactly your code. 这将完全复制您的代码。

Or even easier: 甚至更简单:

def foo(): 
    return condition1 and condition2

You could simplify it like this: 您可以像这样简化它:

def foo:
    if condition1 and condition2:
        return True
    else:
        return False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM