Let's say I have a method definition like this:
def myMethod(a, b, c, d, e)
Then, I have a variable and a tuple like this:
myVariable = 1
myTuple = (2, 3, 4, 5)
Is there a way I can pass explode the tuple so that I can pass its members a开发者_如何学Gos parameters? Something like this (although I know this won't work as the entire tuple is considered the second parameter):
myMethod(myVariable, myTuple)
I'd like to avoid referencing each tuple member individually if possible...
You are looking for the argument unpacking operator *
:
myMethod(myVariable, *myTuple)
From the 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 !
精彩评论