使用堆栈:
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']]]