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

2024-10-01 15:34:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在正在使用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具有此功能?在


Tags: in文档示例for源代码语法range经验
1条回答
网友
1楼 · 发布于 2024-10-01 15:34:28

这是PEP-448: Additional Unpacking Generalizations,这是python3.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}

相关问题 更多 >

    热门问题