- 4.7.4. 解包参数列表
4.7.4. 解包参数列表
当参数已经在列表或元组中但需要为需要单独位置参数的函数调用解包时,会发生相反的情况。例如,内置的 range()
函数需要单独的 start 和 stop 参数。如果它们不能单独使用,请使用 *
运算符编写函数调用以从列表或元组中解包参数:
- >>> list(range(3, 6)) # normal call with separate arguments
- [3, 4, 5]
- >>> args = [3, 6]
- >>> list(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, end=' ')
- ... print("if you put", voltage, "volts through it.", end=' ')
- ... 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 !