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

时间:2014-12-03 17:53:45

标签: python list nested

我正在尝试从平面分隔列表中创建嵌套列表。 举个例子:

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

如何获得嵌套的多级列表:

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

2 个答案:

答案 0 :(得分:1)

使用堆栈:

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']]]

答案 1 :(得分:0)

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