首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Python字典中打印所有Root to Leaf路径

如何在Python字典中打印所有Root to Leaf路径
EN

Stack Overflow用户
提问于 2018-09-06 06:18:24
回答 1查看 0关注 0票数 0

假设我有一个复杂的树型字典列表组合:

代码语言:javascript
复制
dct = {'node': {'a':[1,2,3],
                'b':{'b1':[{'b11':[4,5]},{'b12':[6,7]}],
                     'b2':[8,9]
                    },
                'c':{'c1':[10,11],
                     'c2':[12,13]
                    } 
               }
     }

我有更深层次的结构,我怎样才能以dict或其他形式获得每一组根到叶子路径。

例如路径:

{'node':'a','a':1}

{'node':'a','a':2}

{'node':'a','a':3}

{'node':'b','b':'b1','b1':'b11','b11':5}

{'node':'b','b':'b1','b1':'b11','b11':4}

{'node':'b','b':'b2','b2':9}

同样,我想要所有的路径!

EN

回答 1

Stack Overflow用户

发布于 2018-09-06 15:53:28

你可以使用yield

代码语言:javascript
复制
def get_paths(d, current=[]):
  yield current
  for a, b in d.items():
    if not isinstance(b, list):
      yield from get_paths(b, current+[a])
    else:
      for c in b:
        if not isinstance(c, dict):
           yield current+[a, c]
        else:
           yield from [current+[a]+i for i in get_paths(c)]

d = list(get_paths(dct))
new_d = [{b[i]:b[i+1] for i in range(len(b)-1)} for b in d if len(b) > 1]

输出:

代码语言:javascript
复制
[{'node': 'a', 'a': 1}, {'node': 'a', 'a': 2}, {'node': 'a', 'a': 3}, {'node': 'b'}, {'node': 'b', 'b': 'b1'}, {'node': 'b', 'b': 'b1', 'b1': 'b11', 'b11': 4}, {'node': 'b', 'b': 'b1', 'b1': 'b11', 'b11': 5}, {'node': 'b', 'b': 'b1'}, {'node': 'b', 'b': 'b1', 'b1': 'b12', 'b12': 6}, {'node': 'b', 'b': 'b1', 'b1': 'b12', 'b12': 7}, {'node': 'b', 'b': 'b2', 'b2': 8}, {'node': 'b', 'b': 'b2', 'b2': 9}, {'node': 'c'}, {'node': 'c', 'c': 'c1', 'c1': 10}, {'node': 'c', 'c': 'c1', 'c1': 11}, {'node': 'c', 'c': 'c2', 'c2': 12}, {'node': 'c', 'c': 'c2', 'c2': 13}]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100002571

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档