简体   繁体   English

从元组列表创建树

[英]Creating a tree from a list of tuples

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. Python从左到右对元组进行排序,因此,如果您排列元组,则第一个排序键为第一项,依此类推,这将相当有效。

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 ) (来源: 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? 在这种情况下,“排序”是什么意思?

I'm not sure I've quite follows what you are exactly trying to do, but if you have a forest as a list of nodes, can't you just read it and build the tree structure, then write it out as a bread-first traversal of all the trees? 我不确定我是否完全按照您的实际意图进行操作,但是如果您有一个森林作为节点列表,那么您是否只能阅读并构建树结构,然后将其写成面包-遍历所有树木? Any particular reason to avoid this? 避免这种情况的任何特殊原因?

Oliver, if I understand correctly, I think you can either (a) retrieve all tuples from your database into a dictionary or list, and then construct the tree, OR (b) use an ORDER BY clause when you retrieve the tuples so that they are in the order in which you will add them to the tree. 奥利弗(Oliver),如果我理解正确,我认为您可以(a)从数据库中将所有元组检索到字典或列表中,然后构造树,或者(b)在检索元组时使用ORDER BY子句,以便它们按照将它们添加到树中的顺序。

If changes to the tree may be made in your application and then propagated to the database, I would opt for a, but if changes are always made as database inserts, updates or deletes, and apart from these your tree is read-only, then option b should be faster and require less resources. 如果可以在您的应用程序中对树进行更改,然后将其传播到数据库,那么我会选择a,但是如果更改总是在数据库插入,更新或删除时进行,并且除这些以外,您的树是只读的,则选项b应该更快并且需要更少的资源。

Roland 罗兰

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM