返回多个对象并将它们用作参数

时间:2016-10-06 12:55:33

标签: python function functional-programming return arguments

我有一个类似这样的功能:

def do_something(lis):
    do something
    return lis[0], lis[1]

和另一个需要将这两个返回对象作为参数的函数:

def other_function(arg1, arg2):
    pass

我试过了:

other_function(do_something(lis))

但是发生了这个错误:

  

TypeError:other_function()缺少1个必需的位置参数:'arg2'

2 个答案:

答案 0 :(得分:3)

调用other_function时需要解压缩这些参数。

other_function(*do_something(lis))

根据错误消息,看起来您的其他功能已定义(并应定义为)

def other_function(arg1, arg2):
    pass

因此,当您从do_something返回时,您实际上正在返回包含(lis[0], lis[1])的元组。所以当你最初调用other_function时,你传递一个元组,当你的other_function仍然期待第二个参数时。

如果你进一步细分,你可以看到这一点。下面是对不同处理方式的返回方式的细分,错误的再现以及解决方案的演示:

返回单个变量将返回结果的元组:

>>> def foo():
...     lis = range(10)
...     return lis[1], lis[2]
...
>>> result = foo()
>>> result
(1, 2)

返回两个变量,解压缩到每个var:

>>> res1, res2 = foo()
>>> res1
1
>>> res2
2

尝试使用result调用other_function,现在只保存结果的元组:

>>> def other_function(arg1, arg2):
...     print(arg1, arg2)
...
>>> other_function(result)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: other_function() missing 1 required positional argument: 'arg2'

使用res1res2调用other_function,其中包含foo的每个返回值:

>>> other_function(res1, res2)
1 2

使用result(您的元组结果)并在函数调用中解压缩other_function

>>> other_function(*result)
1 2

答案 1 :(得分:1)

你可以这样做:

other_function(*do_something(list))

*字符会展开tuple返回的do_something

您的do_something函数实际上返回的tuple包含多个值,但 只有一个值本身。

有关详细信息,请参阅the doc