Python:dict of dicts(树)转换成lis

2024-04-25 08:00:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个表示树的dict:

{1: {2: 3, 4: 5}, 6: {7: 8, 9: 10}}

我怎样才能把它变成从根到叶的所有可能的路径?你知道吗

otput应该是smt,如下所示:

[[1,2,3],[1,4,5],[6,7,8],[6,9,10]]

有没有一种Python dict内联程序可以解决任何dict深度的问题?你知道吗


Tags: 路径程序dictsmtotput
1条回答
网友
1楼 · 发布于 2024-04-25 08:00:56

这就是递归的完美之处:

def paths(tree):
    if not isinstance(tree, dict):
        return [[tree]]
    return [[key] + path
            for key, value in tree.items()
            for path in paths(value)]

print(paths({1: {2: 3, 4: 5}, 6: {7: 8, 9: {10: 11, 12: 13}}}))

输出:

[[1, 2, 3], [1, 4, 5], [6, 9, 10, 11], [6, 9, 12, 13], [6, 7, 8]]

相关问题 更多 >