简体   繁体   English

元组中的星号,列表和集合定义,字典定义中的双星号

[英]asterisk in tuple, list and set definitions, double asterisk in dict definition

I'm playing now with Python 3.5 interpreter and found very interesting behavior:我现在正在使用 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'}

I have never seen that neither in documentation and examples nor in any source code despite several years of my Python experience.尽管我有多年的 Python 经验,但我从未在文档和示例中或任何源代码中看到过。 And I found it very useful.我发现它非常有用。

And it seems logical for me from point of view of Python grammar.从 Python 语法的角度来看,这对我来说似乎是合乎逻辑的。 Function arguments and tuple may be parsed with same or similar states.函数参数和元组可以用相同或相似的状态进行解析。

Is it documented behavior?它是记录在案的行为吗? Where is it documented?它在哪里记录?

Which versions of Python have this functionality?哪些版本的 Python 具有此功能?

This is PEP-448: Additional Unpacking Generalizations , which is new in Python 3.5.这是PEP-448: Additional Unpacking Generalizations ,它是 Python 3.5 中的新功能。

The relevant change-log is in https://docs.python.org/3/whatsnew/3.5.html#pep-448-additional-unpacking-generalizations :相关的变更日志在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. PEP 448 扩展了*可迭代解包运算符和**字典解包运算符的允许用途。 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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM