x = ['a', '1', ['c', 'd', ['e', ['f', '123']]]]
def recurse(y):
left,right = [],None
# Here we loop over the elements and whenever we encounter
# another list, we recurse.
for elem in y:
if isinstance(elem,list):
right = recurse(elem)
else:
left.append(elem)
# If there is no further nested list, return only the
# concatenated values, else return the concatenated values
# and the next list in the nest.
if right is None:
return ["".join(left)]
else:
return ["".join(left),right]
print recurse(x)
def collapse(x):
l = deque([x])
result = []
y = ""
while l:
p = l.popleft()
for i in p:
if isinstance(i, list):
result.append(y)
y = ""
l.append(i)
break
else:
y = y + i
result.append(y)
return result
x = ['a', '1', ['c', 'd', ['e', ['f', '123']]]]
j = [ i for i in collapse(x)]
j.reverse()
print reduce(lambda x, y: [y, x], j[1:], [j[0]])
这里的嵌套结构适合递归算法遍历:
结果是:
^{pr2}$下面是一个非递归解决方案:
步骤如下:
它可能不比递归版本优雅,但是如果列表是深嵌套的,它不会炸毁堆栈。在
相关问题 更多 >
编程相关推荐