如何分解元组,以便将其作为参数列表传递?

2024-09-25 01:31:09 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

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

有没有方法可以传递explode元组以便将其成员作为参数传递?类似这样的东西(尽管我知道这不起作用,因为整个元组被认为是第二个参数):

myMethod(myVariable, myTuple)

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


Tags: 方法参数定义def成员元组explodemymethod
2条回答

您正在查找argument unpacking运算符*

myMethod(myVariable, *myTuple)

Python documentation

The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments. For instance, the built-in range() function expects separate start and stop arguments. If they are not available separately, write the function call with the *-operator to unpack the arguments out of a list or tuple:

>>> 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]

In the same fashion, dictionaries can deliver keyword arguments with the **-operator:

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

相关问题 更多 >