Order a list to get a hierarchical order

Ivars Geidans ivars.geidans at gmail.com
Fri Jun 8 06:58:54 EDT 2012


Something like this?

#!/usr/bin/env python3

import random

class Node:
    def __init__(self, parent, name):
        self.parent, self.name = parent, name
    def __repr__(self):
        return self.name

p_1 = Node(None, 'Parent #1')
p_2 = Node(None, 'Parent #2')
c_1_1 = Node(p_1, 'Child #1.1')
c_1_1_1 = Node(c_1_1, 'Child #1.1.1')
c_1_1_2 = Node(c_1_1, 'Child #1.1.2')
c_1_2 = Node(p_1, 'Child #1.2')
c_2_1 = Node(p_2, 'Child #2.1')

node_list = [p_1, p_2, c_1_1, c_1_1_1, c_1_1_2, c_1_2, c_2_1]
random.shuffle(node_list)
print(node_list)

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

print(sort_nodes(node_list))

On Fri, Jun 8, 2012 at 11:10 AM, Thibaut DIRLIK <merwin.irc at gmail.com> wrote:
> Hi,
>
> Having a list of objet with a parent_id attribute pointing to a parent, I
> want to order this list like this :
>
> [Parent #1, Child #1.1, Child#1.1.1, Child#1.1.2, Child#1.2, Parent #2,
> Child #2.1, ...]
>
> Any clue on how to do this ?
>
> Thanks,
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list