避免 "if x: return x"语句的 Pythonic 方法

标签 python if-statement

我有一个方法,它依次调用其他 4 个方法来检查特定条件,并在返回真值时立即返回(不检查以下几个)。

def check_all_conditions():
    x = check_size()
    if x:
        return x

    x = check_color()
    if x:
        return x

    x = check_tone()
    if x:
        return x

    x = check_flavor()
    if x:
        return x
    return None

这似乎是很多行李代码。而不是每个 2 行 if 语句,我宁愿做这样的事情:

x and return x

但那是无效的 Python。我在这里错过了一个简单、优雅的解决方案吗?顺便说一句,在这种情况下,这四种检查方法可能很昂贵,所以我不想多次调用它们。

最佳答案

除了 Martijn 的好答案之外,您还可以链接 。这将返回第一个真值,如果没有真值,则返回 None:

def check_all_conditions():
    return check_size() or check_color() or check_tone() or check_flavor() or None

演示:

>>> x = [] or 0 or {} or -1 or None
>>> x
-1
>>> x = [] or 0 or {} or '' or None
>>> x is None
True

关于避免 "if x: return x"语句的 Pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36117583/

相关文章:

python - Django 中的复合外键

Python性能特点

python - 在 numpy 数组中查找模式的最有效方法

python - 是否可以将 django-celery-beat 与 django-tenant 一起使用?

c - 循环因条件终止,但条件是必要的?

php - 检查多个变量是否都等于 IF 语句中的相同值的简写方法是什么? (PHP)

java - 如何让Java中的扫描仪不关心标点符号

shell - 使用多个 if 语句和 else if 语句之间有什么区别吗?

python - 定位颜色条

javascript - 来自字符串语句的 if 语句