Order a list to get a hierarchical order

Peter Otten __peter__ at web.de
Fri Jun 8 07:47:46 EDT 2012


Ivars Geidans wrote:

> Something like this?

Or this (I'm reusing some of your code but let the built-in sorted() do the 
hard work):

#!/usr/bin/env python3

import random

def _reverse_iterpath(node):
    while node is not None:
        yield node.name
        node = node.parent

def path(node):
    return tuple(_reverse_iterpath(node))[::-1]

class Node:
    def __init__(self, parent, name):
        self.parent = parent
        self.name = name
    def __repr__(self):
        return "/".join(path(self))

def show(caption, node_list):
    print(caption.center(len(caption)+10, "-"))
    for node in node_list:
        print(node)
    print()

if __name__ == "__main__":
    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)

    show("before", node_list)
    show("after", sorted(node_list, key=path))





More information about the Python-list mailing list