ksenia.marasanova at gmail.com
Wed Aug 10 09:28:49 CEST 2005
I have a list that contains nodes from a tree. Each node is a class
instance, but I'll use dictionary here to simplify the example.
So the list looks like this:
'name': 'Parent node',
'name': 'My node',
Where 'ord_number' is the "sibling index". It's not always properly
filled in; sometimes it's the same for several siblings, or doesn't
starts with 1.
I want to sort this list with the following rules:
1. The parent must always come before the children in the list
2. Nodes with the same parent must be sorted by 'ord_number'
The first rule is easy, cause I can use 'url' for it. List with nodes
is coming from the database, so I just do "ORDER BY url".
The second rule is kind of tricky to do in the database. I probably
would need to do something like "ORDER BY
cut_off_lastpart_from_url(url), ord_number". But there seems to be no
native string function in Postgres to do it easily, so I desided to
sort it in Python.
So I've come up with this:
def cmp_tree(x, y):
if x['parent_id'] == y['parent_id']:
return cmp(x['ord_number'], y['ord_number'])
return cmp(x['url'], y['url'])
but it doesn't work as expected. Apparently I don't have a clue about
how sorting function work :(
Can anybody help?
More information about the Python-list