元组,列表和集合定义中的星号,字典定义中的双星号 [英] asterisk in tuple, list and set definitions, double asterisk in dict definition

查看:157
本文介绍了元组,列表和集合定义中的星号,字典定义中的双星号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩Python 3.5解释器,发现了非常有趣的行为:

I'm playing now with Python 3.5 interpreter and found very interesting behavior:

>>> (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经验,但我从未在文档,示例和任何源代码中见过.我发现它非常有用.

I have never seen that neither in documentation and examples nor in any source code despite several years of my Python experience. And I found it very useful.

从Python语法的角度看,这对我来说似乎是合乎逻辑的.函数参数和元组可以使用相同或相似的状态进行解析.

And it seems logical for me from point of view of Python grammar. Function arguments and tuple may be parsed with same or similar states.

是否已记录行为?记录在哪里?

Is it documented behavior? Where is it documented?

哪个版本的Python具有此功能?

Which versions of Python have this functionality?

推荐答案

这是 PEP -448:附加的拆包概述,这是Python 3.5中的新功能.

This is PEP-448: Additional Unpacking Generalizations, which is new in Python 3.5.

相关的更改日志位于 https中://docs.python.org/3/whatsnew/3.5.html#pep-448-additional-unpacking-generalizations :

PEP 448扩展了*可迭代拆包运算符和**字典拆包运算符的允许使用.现在可以在函数调用中使用任意数量的解压缩:

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}

这篇关于元组,列表和集合定义中的星号,字典定义中的双星号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆