Python 中 *tuple 和 **dict 是什么意思? [复制]

2024-02-22

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

What is **的功能在这里?


在函数调用中

*t意思是“将此可迭代的元素视为此函数调用的位置参数”。

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

>>> t = (1, 2)
>>> foo(*t)
1 2

从 v3.5 开始,您还可以在列表/元组/集合文字中执行此操作:

>>> [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 loops

*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

请注意,出现在带星号的参数(标记为*) 仅限关键字:

def f(a, *, b): ...

f(1, b=2)  # fine
f(1, 2)    # error: b is keyword-only

添加了Python3.8仅位置参数 https://docs.python.org/3/whatsnew/3.8.html#positional-only-parameters,表示不能用作关键字参数的参数。他们出现在一个/(双关语*前面的仅关键字参数)。

def f(a, /, p, *, k): ...

f(  1,   2, k=3)  # fine
f(  1, p=2, k=3)  # fine
f(a=1, p=2, k=3)  # error: a is positional-only
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 中 *tuple 和 **dict 是什么意思? [复制] 的相关文章

随机推荐