【问题标题】:What does *tuple and **dict mean in Python? [duplicate]Python 中的 *tuple 和 **dict 是什么意思? [复制]
【发布时间】:2014-03-15 13:41:19
【问题描述】:

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

**在这里的作用是什么?

【问题讨论】:

  • 不是**tuple,而是**dictionary
  • @MartijnPieters 对此很抱歉,我会努力解决的。
  • 没问题,只是指出你的误解。
  • @MartijnPieters 如果您从语言开始,这不是一个重复的问题。对我来说,这个问题给出了与 *arg 和 **kwargs 不同的观点。

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


【解决方案1】:

在函数调用中

*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 循环中

*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 新增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

【讨论】:

  • 不错的答案。我将添加关键字operator,以便在有人搜索python operator ** 期望*** 时更容易找到此答案,这在此上下文中称为运算符。
  • 很好的答案。只是补充一点,在“在函数签名中”的情况下,常见的习惯用法是使用 *args 作为位置参数,使用 **kwargs 作为关键字参数。
  • @GuzmanOjero 这是真的,但前提是没有有意义的替代方案。
猜你喜欢
  • 2016-01-09
  • 2012-12-01
  • 2015-02-13
  • 2019-03-30
  • 2019-04-15
  • 2020-03-26
  • 2019-12-17
  • 2011-12-23
  • 2013-01-30
相关资源
最近更新 更多