python - 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
解决方案
只需将两个结果收集到变量中
a, b = fn()
if a:
# work with b
推荐阅读
- python - 将001格式的数字添加到python中的文件名
- javascript - angular4材质表
- angular - 在Angular 5中使用ngIf作为动态显示模板和隐藏模板
- nginx - 在 nginx 中隐藏一个虚拟文件夹
- parameters - 在 HP ALM 的测试配置中设置参数值的正确方法是什么?
- scikit-learn - sklearn KNN 回归在 k=1 时没有给出 0 的训练错误
- python - 为多个变量赋值时如何迭代dict键
- c - 为什么代码停止并用指针中止执行?
- c++ - 可以使用不可复制的成员作为使对象不可复制的替代方法吗?
- javascript - 使用javascript对数组问题进行排序