• 4.7.4. 解包参数列表

    4.7.4. 解包参数列表

    当参数已经在列表或元组中但需要为需要单独位置参数的函数调用解包时,会发生相反的情况。例如,内置的 range() 函数需要单独的 startstop 参数。如果它们不能单独使用,请使用 * 运算符编写函数调用以从列表或元组中解包参数:

    1. >>> list(range(3, 6)) # normal call with separate arguments
    2. [3, 4, 5]
    3. >>> args = [3, 6]
    4. >>> list(range(*args)) # call with arguments unpacked from a list
    5. [3, 4, 5]

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

    1. >>> def parrot(voltage, state='a stiff', action='voom'):
    2. ... print("-- This parrot wouldn't", action, end=' ')
    3. ... print("if you put", voltage, "volts through it.", end=' ')
    4. ... print("E's", state, "!")
    5. ...
    6. >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
    7. >>> parrot(**d)
    8. -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !