嵌套多级lis的平面分隔列表

2024-04-19 20:01:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从平面分隔列表生成嵌套列表。 例如:

L1=[
'YYYYY', 'OPEN',  ' 111',   ' 222', 'CLOSE', 
'XXXX','OPEN', '  333', '  444', 'OPEN', '    555', '    666', 'CLOSE','CLOSE'
]

如何获取嵌套多级列表:

L2=
[
['YYYYY',
' 111', 
' 222', 
], 
['XXXX',
'  333', 
['  444', 
'    555', 
'    666',
]
]
]

Tags: l1列表closeopen平面xxxxl2yyyyy
2条回答
def flat_list(_list):
    """

    :param _list:
    :return:
    """
    res = []
    if type(_list) is list:
        for item in _list:
            if type(item) is not list:
                res.append(item)
            else:
                [res.append(x) for x in flat_list(item)]
    else:
        res.append(_list)

    return res

使用堆栈:

def build_multilevel(entries):
    result = []
    stack = [result]
    for i, entry in enumerate(entries):
        if entry == 'OPEN':
            # convert last element of the top-most list on the stack
            # to a new, nested list, and push that new list on top
            stack[-1][-1] = [stack[-1][-1]]
            stack.append(stack[-1][-1])
        elif entry == 'CLOSE':
            stack.pop()
        else:
            stack[-1].append(entry)
    return result

演示:

>>> L1=[
... 'YYYYY', 'OPEN',  ' 111',   ' 222', 'CLOSE', 
... 'XXXX','OPEN', '  333', '  444', 'OPEN', '    555', '    666', 'CLOSE','CLOSE'
... ]
>>> def build_multilevel(entries):
...     result = []
...     stack = [result]
...     for i, entry in enumerate(entries):
...         if entry == 'OPEN':
...             # convert last element of the top-most list on the stack
...             # to a new, nested list, and push that new list on top
...             stack[-1][-1] = [stack[-1][-1]]
...             stack.append(stack[-1][-1])
...         elif entry == 'CLOSE':
...             stack.pop()
...         else:
...             stack[-1].append(entry)
...     return result
... 
>>> build_multilevel(L1)
[['YYYYY', ' 111', ' 222'], ['XXXX', '  333', ['  444', '    555', '    666']]]

相关问题 更多 >