从列表到树的表示

时间:2014-04-09 18:33:03

标签: python list recursion tree generator

您好我有一个列表(在Python 3中),如下所示:

lista=[ ['a','b','c','d'],['b','f','g'],['c','h','i'],['d'],['h'],['i'],['f'],['g']]

我试图在像这样的嵌套列表中翻译它

['a',['b',['f'],['g']],['c',['h'],['i']],['d']]]

所以它就像这棵树:

              a
            / | \
          b   c  d
         /\   /\
       f  g   h i 

我想用这样的发电机

listb = [ lista[0][0]] + [x for x in lista[1:] ]

但我不知道如何在整个列表中递归迭代。 谢谢!

2 个答案:

答案 0 :(得分:2)

def nodeinline(head, nodes):
    return [head] + [nodeinline(child, nodes) for child in nodes.get(head, [])]

def nodebyref_to_nodeinline(lst):
    head  = lst[0][0]
    nodes = {node[0]: node[1:] for node in lst}
    return nodeinline(head, nodes)

nodebyref_to_nodeinline([['a','b','c','d'],['b','f','g'],['c','h','i'],['d'],['h'],['i'],['f'],['g']])

给出

['a', ['b', ['f'], ['g']], ['c', ['h'], ['i']], ['d']]

答案 1 :(得分:0)

我认为这应该适合你:

lista=[ ['a','b','c','d'],['b','f','g'],['c','h','i'],['d'],['h'],['i'],['f'],['g']]

def tree(root, d):
    return [root] + [tree(k, d) for k in d[root]]

d = {i[0]: i[1:] for i in lista}

root = 'a'
print(tree(root, d))

打印出来:

['a', ['b', ['f'], ['g']], ['c', ['h'], ['i']], ['d']]

虽然我相信字典(d)本身可能会为你提供更好的服务。