我有一个函数,大部分情况下应该返回单个值,但有时需要从函数返回第二个值。 这里我找到了如何返回多个值,但由于大多数情况下我只需要其中一个值,所以我想编写类似于以下内容的代码:
def test_fun():
return 1,2
def test_call():
x = test_fun()
print x
但调用此功能会导致以下结果:
>>> test_call()
(1,2)
当尝试返回两个以上的内容时,例如:
def test_fun2():
return 1,2,3
def test_call2():
x,y = test_fun2()
print x,y
我遇到了一个错误。
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "my_module.py", line 47, in test_call2
x,y = test_fun2()
ValueError: too many values to unpack
我在思考类似于Matlab的问题,其中x = test_fun()
将导致x == 1
(而[x y] = test_fun()
也可以正常工作)。在Python中是否有类似的功能?
x,*y = ...
是我能得到的最接近的答案。 - 463035818_is_not_a_number*x
的注释。 - Mad Physicist