I seem to be blind at the moment, so I need to ask here. I want to sort a list of tuples which look like that
(id, parent_id, value)
So that it is a representation of the tree as a flattend list of list of tree nodes.
For example the input
(1, None, '...')
(3, 2', '...')
(2, 1, '...')
(4, 1, '...')
(5, 2, '...')
(6, None, '...')
Should sorted like that afterwards
(1, None, '...')
(2, 1, '...')
(3, 2', '...')
(5, 2, '...')
(4, 1, '...')
(6, None, '...')
Any hint would be highly appreciated. Thanks in advance.
Python sorts tuples from left to right, so if you arrange your tuples so the first sort key is the first item and so forth, it’ll be reasonably efficient.
The mapping from a list of tuples to a tree is not clear from what you’re describing. Please draw it out, or explain it more thoroughly. For example, your example appears to be:
(source: sabi.net)
If you’ve got two nodes with no parent, that is more like a forest than a tree. What are you trying to represent with the tree? What does “sorted” mean in this context?