*args 形参接收一个 元组, 形参为 **args 形式时,接收一个字典, *args 必须在 **args 前面

  • *(星号)用于解包序列或可迭代对象,将其元素分配给函数的参数或在列表、元组等数据结构中进行拼接。

  • **(双星号)用于解包字典,将其键值对传递给函数的参数或在字典中进行拼接。

传递可变参数给函数时:

1
2
3
4
5
6
7
8
def cheeseshop(kind, *arguments, **keywords):
    print("-- Do you have any", kind, "?")
    print("-- I'm sorry, we're all out of", kind)
    for arg in arguments:
        print(arg)
    print("-" * 40)
    for kw in keywords:
        print(kw, ":", keywords[kw])

序列解包

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
>>> def multiply(a, b, c):
...     return a * b * c
...
>>> numbers = [1, 2, 3]
>>> multiply(*numbers)
6
>>> numbers = (1, 2, 3)
>>> multiply(*numbers)
6
>>> d = {"a": 1, "b": 2, "c": 3}
>>> multiply(**d)
6

序列拼接

1
2
3
4
5
6
7
8
>>> numbers = [1, 2, 3]
>>> [*numbers, 4, 5, 6]
[1, 2, 3, 4, 5, 6]

>>> d = {"a": 1, "b": 2, "c": 3}
>>> b = {**d, "d": 4, "e": 5}
>>> b
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

参考