如何将元组爆炸以便可以作为参数列表传递?

时间:2010-07-07 19:38:33

标签: python parameters tuples iterable-unpacking

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

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

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

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

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

myMethod(myVariable, myTuple)

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

2 个答案:

答案 0 :(得分:37)

您正在寻找argument unpacking运算符*

myMethod(myVariable, *myTuple)

答案 1 :(得分:7)

来自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 !