【问题标题】:How can I explode a tuple so that it can be passed as a parameter list?如何分解一个元组以便它可以作为参数列表传递?
【发布时间】:2010-07-07 19:38:32
【问题描述】:

假设我有一个这样的方法定义:

def myMethod(a, b, c, d, e)

然后,我有一个变量和一个像这样的元组:

myVariable = 1
myTuple = (2, 3, 4, 5)

有没有办法可以通过爆炸元组,以便我可以将其成员作为参数传递?像这样的东西(虽然我知道这不会起作用,因为整个元组被认为是第二个参数):

myMethod(myVariable, myTuple)

如果可能,我想避免单独引用每个元组成员...

【问题讨论】:

标签: python parameters tuples iterable-unpacking


【解决方案1】:

您正在寻找argument unpacking 运算符*

myMethod(myVariable, *myTuple)

【讨论】:

  • 很好,谢谢! (我以为我读过一种方法……不过对 Python 来说还是很新,不知道如何搜索它。)
  • @froadie:对,曾经有——实际上,现在仍然是——一个名为apply 的函数,它可以起到与星号和双星号运算符相同的作用。但是apply 已被弃用,取而代之的是 * 和 **。 (见docs.python.org/library/functions.html#apply
  • 也适用于可迭代对象,与手册相反,手册中说它必须是一个序列。
【解决方案2】:

来自Python documentation

相反的情况发生在当 参数已经在列表中或 元组,但需要解包 需要单独的函数调用 位置论据。例如, 内置 range() 函数需要 单独的开始和停止参数。如果 它们不能单独使用, 用 *-operator 从列表或元组中解压缩参数:

>>> range(3, 6)             # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)            # call with arguments unpacked from a list
[3, 4, 5]

以同样的方式,字典可以 传递关键字参数 **-运营商:

>>> def parrot(voltage, state='a stiff', action='voom'):
...     print "-- This parrot wouldn't", action,
...     print "if you put", voltage, "volts through it.",
...     print "E's", state, "!"
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

【讨论】:

    猜你喜欢
    • 2017-05-20
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多