Order a list to get a hierarchical order

Thibaut DIRLIK merwin.irc at gmail.com
Fri Jun 8 09:07:26 EDT 2012


Thanks for your help, I'll test this.

2012/6/8 Peter Otten <__peter__ at web.de>

> Ivars Geidans wrote:
>
> > def append_node(n, l, ls):
> >     ls.append(n)
> >     for c in [nc for nc in l if nc.parent is n]:
> >         append_node(c, l, ls)
> >     return ls
> >
> > def sort_nodes(l):
> >     ls = []
> >     for r in l:
> >         if r.parent == None:
> >             append_node(r, l, ls)
> >
> >     return ls
>
> This ensures that child nodes appear after their parent but leaves the
> order
> of nodes on the same level undefined. I think adding
>
> def sort_nodes(l):
>      l = sorted(l, key=lambda node: node.name) #untested
>      ...
>
> would fix that.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120608/394ccbd6/attachment.html>


More information about the Python-list mailing list