--- fid: 20231204-100937 tags: unpack, star-operator --- (star-operator)= # Python 星号解包 2023-12-04 Python 中,单星号`*`和双星号`**`除了作为“乘”和“幂”的数值运算符外,还在列表、元组、字典的操作、函数的传参等方面中有着重要作用。 ## *list, *tuple 列表前面加星号作用是将列表解开(unpack)成多个独立的参数,传入函数。 1 ```python def add(a, b): return a + b data = [7, 8] print(add(*data)) #= 15 ``` 2 ```python import numpy as np print(np.arange(3,6)) #= [3 4 5] # 等效写法: list2 = (3, 6) print(np.arange(*list2)) #= [3 4 5] ``` ## **dict 字典前面加两个星号,是将字典解开成为独立的元素作为形参。 3 ```python def add(a, b): return a + b data = {'a':7, 'b':8} print(add(**data)) # 15 ```