如何展开元组以作为参数列表传递?

24 投票
2 回答
17264 浏览
提问于 2025-04-16 00:57

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

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

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

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

有没有办法让我把这个元组里的内容拆开,这样我就可以把它们当作参数传递?就像这样(虽然我知道这样做不行,因为整个元组会被当作第二个参数):

myMethod(myVariable, myTuple)

如果可以的话,我希望能避免单独引用每个元组里的成员……

2 个回答

7

来自Python文档的内容:

有时候,我们的参数已经放在一个列表或元组里,但在调用函数时需要把它们拆开,变成单独的参数。比如,内置的range()函数就需要单独的起始和结束参数。如果你没有单独的参数,可以用*-操作符来把列表或元组里的参数拆开,传给函数:

>>> 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 !
47

你在寻找的是 参数解包 操作符 *

myMethod(myVariable, *myTuple)

撰写回答