我正在尝试从平面分隔列表中创建嵌套列表。 举个例子:
L1=[
'YYYYY', 'OPEN', ' 111', ' 222', 'CLOSE',
'XXXX','OPEN', ' 333', ' 444', 'OPEN', ' 555', ' 666', 'CLOSE','CLOSE'
]
如何获得嵌套的多级列表:
L2=
[
['YYYYY',
' 111',
' 222',
],
['XXXX',
' 333',
[' 444',
' 555',
' 666',
]
]
]
答案 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