python - 由内而外迭代嵌套列表

标签 python python-3.x

我有以下 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)

希望这能解释我的问题,感谢您的帮助

最佳答案

您正在寻找的是结构的后序遍历:

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']

关于python - 由内而外迭代嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14960380/

相关文章:

python - 关于 __getattr__ 和 __getattribute__ 的一些问题?

python - 在 OpenCV 中检测二进制 blob

python - django 应用程序中的每个 url 只呈现 home.html

python-3.x - 如何在 python 中使用 mpi4py 库连接收集的数据

python - 可移植Python/IPython

python-3.x - telethon.errors.rpcerrorlist.FloodWaitError : A wait of 41548 seconds is required (caused by InviteToChannelRequest)

python - 如何在 Python 中为类型定义别名以进行类型提示

python - 如何使用 Python 获取树的叶节点?

python - 如何使用 python 更新、旋转和显示 ply 文件?

python - 无法确定Cassandra中Select查询速度慢的原因