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

后端 未结 2 755
忘了有多久
忘了有多久 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.

提交回复
热议问题