python的解包操作符*和**怎么用?

How are python's unpacking operators * and ** used?

unpacking/splat 运算符 *** 在 python 版本(2.7、3.x < 3.5 和 3.x >= 3.5).

例如:

                                   |   2.7    |   3.1-3.4  |   3.5   
----------------------------------------------------------------------
function(*args)                         ✓            ✓          ✓    

x, *y, z = [1, 2, 3, 4, 5]              x            ✓          ✓    

{**x, **y}                              x            x          ✓    

还有我遗漏的各种版本之间的差异吗?我正在查看 PEP 和自述文件,但文档没有对此进行详细说明。

1992 年左右(不确定 Python 版本)。这是来自 Python 1.0.1.

的语法文件
# 06-Apr-92:
#   Use only '*' for varargs list

# 31-Mar-92:
#   Tighten syntax for try statements

# 27-Feb-92:
#   Allow NEWLINE* after eval input

# 16-Jan-92:
#   Added '*' as alternative for '+' in varargs syntax
#   (Not sure which alternative is better yet.)

# 11-Jan-92:
#   Variable length argument list syntax added: def f(a, b, +rest): ...

Python 1.4+:

Keyword Arguments: Functions and methods written in Python can now be called using keyword arguments of the form keyword = value.

Python 1.6+

There's now special syntax that you can use instead of the apply() function. f(*args, **kwds) is equivalent to apply(f, args, kwds). You can also use variations f(a1, a2, *args, **kwds) and you can leave one or the other out: f(*args), f(**kwds).

Python <= 2.7:

在 Python 3.0 中删除了元组参数解包。

PEP 3113: Tuple parameter unpacking removed. You can no longer write def foo(a, (b, c)): .... Use def foo(a, b_c): b, c = b_c instead.

Python 3.0+

PEP 3132: Extended Iterable Unpacking. You can now write things like a, b, *rest = some_sequence. And even *rest, a = stuff. The rest object is always a (possibly empty) list; the right-hand side may be any iterable.

PEP 3102: Keyword-only arguments. Named parameters occurring after *args in the parameter list must be specified using keyword syntax in the call. You can also use a bare * in the parameter list to indicate that you don’t accept a variable-length argument list, but you do have keyword-only arguments

Python 3.5+

PEP 448, additional unpacking generalizations.


据我所知,没有一个页面列出所有语法更改。 What's new in Python 部分列出了每个版本的语法更改,或者您可以查看每个版本的语法规范以查看差异。