可选的多个返回值

时间:2018-03-08 08:37:57

标签: python function return-value

我有一个函数,大多数时候应该返回一个值,但有时我需要从函数返回的第二个值。 Here我发现了如何返回多个值,但是大部分时间我只需要其中一个值,我想写这样的东西:

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中有类似的东西吗?

2 个答案:

答案 0 :(得分:10)

您可以使用星形解包将所有其他返回值收集到列表中:

x, *y = fun()

x将包含第一个返回值。 y将是剩余值的列表。如果只有一个返回值,y将为空。此特定示例仅在函数返回元组时才有效,即使只有一个值。

fun始终返回1或2个值时,您可以执行

if y:
    print(y[0])
else:
    print('only one value')

另一方面,如果要完全忽略返回值的数量,请执行

*x = fun()

现在所有的参数都会被收集到列表中。然后,您可以使用

打印它
print(x)

print(*x)

后者将每个元素作为单独的参数传递,就像你做的那样

x, y, z = fun()
print(x, y, z)

使用*x = fun()而不是x = fun()的原因是当函数返回不是元组的东西时立即出错。将其视为提醒您正确撰写fun的断言。

由于这种形式的星形解包仅适用于Python 3,因此Python 2中唯一的选择就是

x = fun()

并手动检查结果。

答案 1 :(得分:1)

有多种方法可以获得多个返回值。

示例1:

def test_fun():
    return 1,2

def test_call():
    x, y = test_fun()
    print x
    print y

您将获得正确的输出:

1
2

如果您想忽略多个返回值,可以在 python3 中的变量之前使用*

示例2:

def test_fun2():
    return 1,2,3

def test_call2():
    x, *y = test_fun2()
    print x
    print y

你会得到结果:

1
(2, 3)