【问题标题】:Use a function with multiple results as arguments [duplicate]使用具有多个结果的函数作为参数[重复]
【发布时间】:2018-10-08 16:21:41
【问题描述】:

我有一个返回多个值的函数,我可以以某种方式直接在另一个函数的参数列表中使用该函数吗?当我(天真地)尝试时,我得到:

def one() :
    return 3, 2
def two(a, b):
    return a + b
two(one())
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-86-27980b86a2c0> in <module>()
  3 def two(a, b):
  4     return a + b
----> 5 two(one())

TypeError: two() missing 1 required positional argument: 'b'

我当然可以做类似的事情

def one() :
    return 3, 2
def two(a, b):
    return a + b
a, b = one()
two(a, b)

【问题讨论】:

  • 作为对为什么的解释,它只是一个参数,one() 返回一个元组 - return 实际上只返回一个对象,尽管这当然可以是一个其他对象的元组。
  • 事实上它是一个副本的副本。有时很难以正确的方式提出我的问题,尤其是在为我学习新的编程语言时。感谢您的回答。

标签: python function parameter-passing


【解决方案1】:

当然。

two(*one())

* 是参数解包

有用的阅读:Understanding the asterisk(*) of Python

【讨论】:

    猜你喜欢
    • 2018-01-24
    • 1970-01-01
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    相关资源
    最近更新 更多