关于*和**运算符

最近了解到*和**运算符的用法,特此小记。

最开始遇到的情形是这样的:我从另一个地方得到了一个tuple a:

a = (1,2)

想把这个tuple里的值作为另一个函数f的参数传给它,理论上完全可以用[]把每个值取出来再一个一个传给函数:

def f(x, y):
    return x + y
f(a[0], a[1])

但这样写也太蠢了,而且当这里参数的个数不是两个而是很多的时候,这样写也太麻烦了。Google一番之后了解到有*运算符这种神奇的东西,有了它,上面的写法可以简化为:

f(*a)

官方文档中也有相关的说明:

4.7.4. Unpacking Argument Lists

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:

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

在自己尝试的过程中也发现了两个有意思的用法:

>>> a = [1,2,3]
>>> print(a)
>>> [1, 2, 3]
>>> print(*a)
>>> 1 2 3

>>> a = [1,2]
>>> [4,5,a,7,8]
>>> [4, 5, [1, 2], 7, 8]
>>> [4,5,*a,7,8]
>>> [4, 5, 1, 2, 7, 8]

Contents


本作品采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。

知识共享许可协议