元组、列表和集合定义中的星号,字典定义中的双星号
asterisk in tuple, list and set definitions, double asterisk in dict definition
我现在正在玩 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 的哪些版本具有此功能?
这是 PEP-448: Additional Unpacking Generalizations,这是 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}
我现在正在玩 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 的哪些版本具有此功能?
这是 PEP-448: Additional Unpacking Generalizations,这是 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}