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

heL*_*maN 18 python tuples namedtuple python-3.x 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)
Run Code Online (Sandbox Code Playgroud)

在同一部分,**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)
Run Code Online (Sandbox Code Playgroud)

什么是**这里的功能?

Ela*_*zar 41

在函数调用中

*t 表示"将此元组的元素视为此函数调用的位置参数."

def foo(x, y):
    print(x, y)

>>> t = (1, 2)
>>> foo(*t)
1 2
Run Code Online (Sandbox Code Playgroud)

从v3.5开始,你也可以在list/tuple/set literals中执行此操作:

>>> [1, *(2, 3), 4]
[1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

**d 表示"将字典中的键值对视为此函数调用的附加命名参数."

def foo(x, y):
    print(x, y)

>>> d = {'x':1, 'y':2}
>>> foo(**d)
1 2
Run Code Online (Sandbox Code Playgroud)

从v3.5开始,您也可以在字典文字中执行此操作:

>>> d = {'a': 1}
>>> {'b': 2, **d}
{'b': 2, 'a': 1}
Run Code Online (Sandbox Code Playgroud)

在功能签名中

*t 表示"获取此函数的所有其他位置参数,并将它们作为元组打包到此参数中."

def foo(*t):
    print(t)

>>> foo(1, 2)
(1, 2)
Run Code Online (Sandbox Code Playgroud)

**d 表示"获取此函数的所有其他命名参数,并将它们作为字典条目插入此参数中."

def foo(**d):
    print(d)

>>> foo(x=1, y=2)
{'y': 2, 'x': 1}
Run Code Online (Sandbox Code Playgroud)

在作业和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
Run Code Online (Sandbox Code Playgroud)

  • 很好的答案。我将添加关键字“operator”,以便当有人搜索“python 运算符 **”并期望“*”或“**”时更容易找到答案,在这种情况下这称为运算符。 (3认同)
  • 很好的答案。只是补充一下,在“在函数签名中”的情况下,常见的习惯用法是使用 *args 作为位置参数,使用 **kwargs 作为关键字参数。 (2认同)
  • @GuzmanOjero 这是真的,但前提是没有有意义的替代方案。 (2认同)