首页 > 解决方案 > 创建嵌套/递归列表

问题描述

如何递归创建列表?

我有这个清单:

l = ['a', 'b', 'new', 'c', 'd', 'new', 'z', 'x', 'c', 'fin', 'f', 'fin', 
     'g', 'l', 'new', 'z', 'x', 'c', 'fin', 'j']

预期的输出是:

r = ['a', 'b', ['c', 'd', ['z', 'x', 'c'] 'f'], 'g', 'l', ['z', 'x', 'c'] 'j']

到目前为止我已经尝试过:

def asd(l, index=0):
    r = []
    for i in l[index:]:
        index += 1
        if i == 'new':
            i, index = asd(l, index)
        r.append(i)
        if i == 'fin':
            return r
    return r, index

r, index = asd(l)

我无法理解如何使它工作。谁能帮我?

标签: pythonlist

解决方案


这是一种非递归解决方案,可以创建您的列表,一次解析,无需任何昂贵的index()操作:

l = ['a', 'b', 'new', 'c', 'd', 'new', 'f', 'fin', 'g', 'fin', 'j']

rv = []

curr = [rv]  # things are always added to the last element if not 'fin' or 'new'

for elem in l:
    if elem == "new":
        # create a new list, put it at end of curr 
        curr.append([])
        # add that list to the one before
        curr[-2].append(curr[-1])
    elif elem == "fin":
        # done, remove from curr
        curr.pop() 
    else:
        curr[-1].append(elem)

print(rv)

输出:

['a', 'b', ['c', 'd', ['f'], 'g'], 'j']

l = ['a', 'b', 'new', '1', '2', '3', 'fin', 'c', 'new', 'x', 'y', 'z', 'fin',]  

导致

['a', 'b', ['1', '2', '3'], 'c', ['x', 'y', 'z']]

您需要对不平衡/不正确new/fin的情况进行万无一失


在 Matthieu 发表评论后进行了编辑以使其更加简洁。


推荐阅读