这篇主要探讨 ** 和 * 前缀运算符,**在变量之前使用的*and **运算符.
简单示例:
>>> numbers = [2, 1, 3, 4, 7]
>>> more_numbers = [*numbers, 11, 18]
>>> print(*more_numbers, sep=', ')
2, 1, 3, 4, 7, 11, 18
用途:
- 使用 * 和 ** 将参数传递给函数
- 使用**和**捕获传递给函数的参数
- 使用*只接受关键字参数
- 使用*元组拆包过程中捕获项目
- 使用*解包iterables到一个列表/元组
- 使用**要解压缩词典到其他字典
例子解释:
-
调用函数时,*可以使用运算符将可迭代对象解压缩为函数调用中的参数:
>>> fruits = ['lemon', 'pear', 'watermelon', 'tomato'] >>> print(fruits[0], fruits[1], fruits[2], fruits[3]) lemon pear watermelon tomato >>> print(*fruits) lemon pear watermelon tomato
该print(*fruits)行将fruits列表中的所有项目print作为单独的参数传递到函数调用中,而我们甚至不需要知道列表中有多少个参数。
-
** 运算符允许我们采取键值对的字典,并把它解压到函数调用中的关键字参数。
>>> date_info = {'year': "2020", 'month': "01", 'day': "01"} >>> filename = "{year}-{month}-{day}.txt".format(**date_info) >>> filename '2020-01-01.txt'
** 将关键字参数解包到函数调用中并不是很常见。我最常看到的地方是练习继承时:super()通常要同时包含*和**。
双方*并 **可以在函数调用中多次使用,像Python 3.5的。>> fruits = ['lemon', 'pear', 'watermelon', 'tomato'] >>> numbers = [2, 1, 3, 4, 7] >>> print(*numbers, *fruits) 2 1 3 4 7 lemon pear watermelon tomato **多次使用类似: >>> date_info = {'year': "2020", 'month': "01", 'day': "