2024-04-25 08:00:56 发布
网友
我有一个表示树的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深度的问题?你知道吗
这就是递归的完美之处:
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]]
这就是递归的完美之处:
输出:
相关问题 更多 >
编程相关推荐