asterisk in tuple, list and set definitions, double asterisk in dict definition

后端 未结 1 795
遇见更好的自我
遇见更好的自我 2020-11-30 09:23

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\', \'o         


        
相关标签:
1条回答
  • 2020-11-30 09:57

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

    The relevant change-log is in 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}
    
    0 讨论(0)
提交回复
热议问题