元组、列表和集合定义中的星号,字典定义中的双星号是什么意思?

20

我现在正在使用Python 3.5解释器进行编程,并发现了非常有趣的行为:

>>> (1,2,3,"a",*("oi", "oi")*3)
(1, 2, 3, 'a', 'oi', 'oi', 'oi', 'oi', 'oi', 'oi')
>>> [1,2,3,"a",*range(10)]
[1, 2, 3, 'a', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ('aw','aw',*range(10),*(x**2 for x in range(10)))
('aw', 'aw', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 4, 9, 16, 25, 36, 49, 64, 81)
>>> {"trali":"vali", **dict(q=1,p=2)}
{'q': 1, 'p': 2, 'trali': 'vali'}
>>> {"a",1,11,*range(5)}
{0, 1, 2, 3, 4, 11, 'a'}

尽管我有多年的Python经验,但在文档、示例和任何源代码中都从未见过这种用法。但我发现它非常有用。

就Python语法而言,从我的角度来看,似乎很合理。函数参数和元组可以使用相同或类似的状态进行解析。

这是被记录下来的行为吗?在哪里记录了呢?

哪些Python版本具有此功能?


1
这只是 *** 解包。你熟悉这个吗? - TigerhawkT3
@TigerhawkT3 不是。但现在我知道它被称为“解包”。我在函数调用中经常使用它,但从未在这种情况下使用过。 - George Sovetov
我猜你正在使用3.5版本,它有扩展功能。在我的这台机器上,它不能在3.4版本上运行,而我只在另一台PC上安装了3.5版本。(不用担心,我现在注意到你正在使用3.5版本了。) - TigerhawkT3
1个回答

32
这是PEP-448:附加解包概述,它是Python 3.5中的新功能。
相关的变更日志在https://docs.python.org/3/whatsnew/3.5.html#pep-448-additional-unpacking-generalizations中:

PEP 448 extends the allowed uses of the * iterable unpacking operator and ** dictionary unpacking operator. It is now possible to use an arbitrary number of unpackings in function calls:

>>>

>>> print(*[1], *[2], 3, *[4, 5])
1 2 3 4 5

>>> def fn(a, b, c, d):
...     print(a, b, c, d)
...

>>> fn(**{'a': 1, 'c': 3}, **{'b': 2, 'd': 4})
1 2 3 4

Similarly, tuple, list, set, and dictionary displays allow multiple unpackings:

>>>

>>> *range(4), 4
(0, 1, 2, 3, 4)

>>> [*range(4), 4]
[0, 1, 2, 3, 4]

>>> {*range(4), 4, *(5, 6, 7)}
{0, 1, 2, 3, 4, 5, 6, 7}

>>> {'x': 1, **{'y': 2}}
{'x': 1, 'y': 2}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接