从内到外遍历嵌套列表
我有一个这样的Python嵌套列表结构:
test = ['a', ['c', ['e'], 'd'], 'b']
或者同样的,只是格式化了一下:
test = [
'a',
[
'c',
[
'e'
],
'd'
],
'b'
]
我在想,最好的方法是什么,来遍历这个完整的列表,从最里面的嵌套列表对象('e')开始,到最外面的列表('a', [...], 'b')以反向顺序进行。直接调用reversed(test)并不能解决嵌套列表的问题。而且在每一层遍历时,还应该能调用一个回调函数。
遍历的结果应该看起来像这样([xx]表示之前调用回调函数计算出的值):
1st e --> callback(e)
2nd c [e] d --> callback(c [e] d)
3rd a [c e d] b --> callback(a [c e d] b)
希望这能解释我的问题,感谢你的帮助。
2 个回答
6
我可以提一个可能的解决办法:
>>> def foo(test):
queue = []
try:
while True:
queue.append(test)
test = test[1]
except IndexError:
for e in reversed(queue):
yield e
>>> data = foo(test)
>>> next(data)
['e']
>>> next(data)
['c', ['e'], 'd']
>>> next(data)
['a', ['c', ['e'], 'd'], 'b']
>>> next(data)
Traceback (most recent call last):
File "<pyshell#753>", line 1, in <module>
next(data)
StopIteration
>>>
它是怎么工作的
- 先深度遍历,把元素放进一个队列里
- 然后反向遍历这个队列,依次输出元素
6
你要找的是这个结构的 后序遍历:
def traverse(l):
for x in l:
if isinstance(x, list):
traverse(x)
callback(l)
如果把 callback
定义为 print
,那么我们得到:
['e']
['c', ['e'], 'd']
['a', ['c', ['e'], 'd'], 'b']