* tuple和** dict在Python中意味着什么?

时间:2014-02-16 08:50:45

标签: python python-3.x tuples namedtuple iterable-unpacking

正如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)

这里的**功能是什么?

1 个答案:

答案 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