Order a list to get a hierarchical order

Peter Otten __peter__ at web.de
Fri Jun 8 08:10:13 EDT 2012


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.


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /