正如PythonCookbook中所提到的,*
可以在元组之前添加,*
在这里是什么意思?
第1.18章。将名称映射到序列元素:
from collections import namedtuple
Stock = namedtuple('Stock', ['name', 'shares', 'price'])
s = Stock(*rec)
# here rec is an ordinary tuple, for example: rec = ('ACME', 100, 123.45)
在同一部分中,**dict
显示:
from collections import namedtuple
Stock = namedtuple('Stock', ['name', 'shares', 'price', 'date', 'time'])
# Create a prototype instance
stock_prototype = Stock('', 0, 0.0, None, None)
# Function to convert a dictionary to a Stock
def dict_to_stock(s):
return stock_prototype._replace(**s)
这里的**
功能是什么?
答案 0 :(得分:31)
*t
表示“将此元组的元素视为此函数调用的位置参数。”
def foo(x, y):
print(x, y)
>>> t = (1, 2)
>>> foo(*t)
1 2
从v3.5开始,你也可以在list / tuple / set literals中执行此操作:
>>> [1, *(2, 3), 4]
[1, 2, 3, 4]
**d
表示“将字典中的键值对视为此函数调用的附加命名参数。”
def foo(x, y):
print(x, y)
>>> d = {'x':1, 'y':2}
>>> foo(**d)
1 2
从v3.5开始,您也可以在字典文字中执行此操作:
>>> d = {'a': 1}
>>> {'b': 2, **d}
{'b': 2, 'a': 1}
*t
表示“获取此函数的所有其他位置参数,并将它们作为元组打包到此参数中。”
def foo(*t):
print(t)
>>> foo(1, 2)
(1, 2)
**d
表示“将此函数的所有其他命名参数作为字典条目插入此参数中。”
def foo(**d):
print(d)
>>> foo(x=1, y=2)
{'y': 2, 'x': 1}
for
循环 *x
表示“消耗右侧的其他元素”,但不一定是最后一项。请注意,x
始终是一个列表:
>>> x, *xs = (1, 2, 3, 4)
>>> x
1
>>> xs
[2, 3, 4]
>>> *xs, x = (1, 2, 3, 4)
>>> xs
[1, 2, 3]
>>> x
4
>>> x, *xs, y = (1, 2, 3, 4)
>>> x
1
>>> xs
[2, 3]
>>> y
4
>>> for (x, *y, z) in [ (1, 2, 3, 4) ]: print(x, y, z)
...
1 [2, 3] 4