我正在开发一个通常返回 1 个值但有时返回 2 的函数,原因与 this post 类似。 ,并注意到这个例子最好地说明了一些意想不到的行为:
def testfcn1(return_two=False):
a = 10
return a, a*2 if return_two else a
def testfcn2(return_two=False):
a = 10
if return_two:
return a, a*2
return a
我希望这两个函数的行为方式相同。 testfcn2 按预期工作:
testfcn2(False)
10
testfcn2(True)
(10, 20)
然而,testfcn1 始终返回两个值,如果 return_two 为 False,则只返回第一个值两次:
testfcn1(False)
(10, 10)
testfcn1(True)
(10, 20)
这种行为有合理的理由吗?
最佳答案
在您的 testfcn1
中,表达式被分组为 -
(a, (a*2 if return_two else a)) #This would always return a tuple of 2 values.
而不是(你认为的那样)-
(a, a*2) if return_two else a #This can return a tuple if return_two is True otherwise a single value `a` .
如果你想要第二组表达式,你必须像我上面那样使用方括号。
显示差异的示例 -
>>> 10, 20 if True else 10
(10, 20)
>>> 10, 20 if False else 10
(10, 10)
>>>
>>>
>>> (10, 20) if False else 10
10
>>> (10, 20) if True else 10
(10, 20)
>>>
>>>
>>> 10, (20 if False else 10)
(10, 10)
>>> 10, (20 if True else 10)
(10, 20)
关于python - 意外的 python 函数返回行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32654860/