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

fro*_*die 20 python parameters tuples iterable-unpacking

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

def myMethod(a, b, c, d, e)
Run Code Online (Sandbox Code Playgroud)

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

myVariable = 1
myTuple = (2, 3, 4, 5)
Run Code Online (Sandbox Code Playgroud)

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

myMethod(myVariable, myTuple)
Run Code Online (Sandbox Code Playgroud)

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

unu*_*tbu 37

您正在寻找参数解包运算符*:

myMethod(myVariable, *myTuple)
Run Code Online (Sandbox Code Playgroud)

  • 也适用于列表(为了OP的利益) (2认同)

Esc*_*alo 7

Python文档:

当参数已经在列表或元组中但需要为需要单独位置参数的函数调用解包时,会发生相反的情况.例如,内置的range()函数需要单独的start和stop参数.如果它们不是单独可用的,请使用*-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]
Run Code Online (Sandbox Code Playgroud)

以同样的方式,字典可以使用** - 运算符提供关键字参数:

>>> 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 !
Run Code Online (Sandbox Code Playgroud)