根据第一个元素长度递归地将列表拆分为子列表

Tyt*_*ans -2 python recursion split list multidimensional-array

我正在解决这个小问题,我确信可以(并且应该)递归地解决它。

# split list in sublists based on length of first element. 
list = [3, 1, 2, 3, 4, 1, 2, 3, 4]
       #*          #*

# *number of elements of the sublist    

Run Code Online (Sandbox Code Playgroud)

显示比解释要好,上面的结果应该是:

[[1, 2, 3], [1, 2, 3, 4]]
Run Code Online (Sandbox Code Playgroud)

我正在处理的列表始终遵循此逻辑,第一个元素始终是以下 n 个元素的长度。

编辑:

根据一些建议,我只是添加了一个 yield 来懒惰地完成它。

def split(ls):
    """
    func that given a list extracts sub lists with the length indicated by the first element
    [2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4] => [[1, 2], [1, 2, 3], [1, 2, 3, 4]]
    """
    res = []
    while ls:
        dim = ls[0]
        yield ls[1:dim + 1]
        ls = ls[dim + 1:]

    return res

>>> list(split([2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4]))
[[1, 2], [1, 2, 3], [1, 2, 3, 4]]
Run Code Online (Sandbox Code Playgroud)

len*_*nik 5

简单的切片会做:

>>> a = [3, 1, 2, 3, 4, 1, 2, 3, 4]
>>> c = []
>>> while len(a) :
...     b = a[0]
...     c.append( a[1:b+1] )
...     a = a[b+1:]
... 
>>> c
[[1, 2, 3], [1, 2, 3, 4]]
Run Code Online (Sandbox Code Playgroud)