python - From list to tree representation -


hello have list (in python 3) :

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

and i'm trying translate in nested list this

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

so it's tree :

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

i thought use generator this

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

but don't know how iterate recursively through whole list. thank you!

i think should work you:

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) k in d[root]]  d = {i[0]: i[1:] in lista}  root = 'a' print(tree(root, d)) 

which prints out:

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

although believe dictionary (d) might serve better.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -