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']]]
使用堆栈:
演示:
相关问题 更多 >
编程相关推荐