Making a tree out of a 2 column list
Peter Otten
__peter__ at web.de
Sun Apr 15 01:13:26 EDT 2007
Sebastian Bassi wrote:
> On 14 Apr 2007 09:32:07 -0700, mensanator at aol.com <mensanator at aol.com>
wrote:
>
> > def tree_path(key,tree,indent):
> > print '\t'*indent,key
> > if tree.has_key(key):
> > for m in tree[key]:
> > tree_path(m,tree,indent+1)
> > return
>
> Thank you. It worked!.
> I changed it a bit to return a list with the results:
>
> def tree_path(key,tree,hijos):
> hijos.append(key)
> if tree.has_key(key):
> for m in tree[key]:
> tree_path(m,tree,hijos)
> return hijos
>
> Then I call it like this:
>
> MyList=tree_path(9608,tree,[])
Depending on your input data you may need to add some cycle detection.
For example, try it with
tree_path(1, {1:[2], 2:[1]}, [])
Peter
More information about the Python-list
mailing list