首页 > 解决方案 > Python:使用在 If 语句中返回两个项目的函数,而不执行两次

问题描述

我有一个函数用于在 if/then 中进行测试。

问题是我在 if 条件中执行函数 BOTH,然后在 if 语句之后再次执行,因为该函数返回两个项目。

这似乎很浪费,我正在想办法改进这一点。这是我试图避免的一个非常基本的版本:返回“True”以允许条件通过,但随后再次执行“coolstuff()”以从函数中获取更多信息。

"coolstuff()"可能返回 false,所以我不能使用返回的字符串 "stuff" 作为测试。

def coolstuff():
    return True, "stuff"
    
if coolstuff()[0]:
    coolthing = coolstuff()[1]
    print coolthing

必须有更好的方法来做到这一点,不是吗?当我试图把它弄清楚时,我的大脑正在融化。

我基本上想做这样的事情(无效)语法:

def coolstuff():
    return True, "stuff"
    
if a, b == coolstuff() and a:
    print b

标签: pythonfunctionif-statement

解决方案


只需将两个结果收集到变量中

a, b = fn()
if a:
    # work with b

推荐阅读