Multiple Unpacking Assignment in Python when you don't know the sequence length

后端 未结 2 746
忘了有多久
忘了有多久 2020-12-03 14:52

The textbook examples of multiple unpacking assignment are something like:

import numpy as NP
M = NP.arange(5)
a, b, c, d, e = M
# so of course, a = 0, b = 1         


        
相关标签:
2条回答
  • 2020-12-03 15:04

    Syntax for this is added to Python 3

    >>> # Python 3.x only
    >>> a, b, *c = range(10)
    >>> a
    0
    >>> b
    1
    >>> c
    [2, 3, 4, 5, 6, 7, 8, 9]
    

    but no similar solution exists in Python 2.

    You can of course do

    >>> s = range(10)
    >>> s
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> (a, b, c), rest = s[0:3], s[3:]
    >>> a
    0
    >>> b
    1
    >>> c
    2
    >>> rest
    [3, 4, 5, 6, 7, 8, 9]
    

    or other similar solutions.

    0 讨论(0)
  • 2020-12-03 15:05

    Python 3.x can do this easily:

    a, b, *c = someseq
    

    Python 2.x needs a bit more work:

    (a, b), c = someseq[:2], someseq[2:]
    
    0 讨论(0)
提交回复
热议问题