Python 使用哪种算法以树状结构填充数据
我的数据库中有这个表,我想在wabpage上填充数据Python 使用哪种算法以树状结构填充数据,python,algorithm,Python,Algorithm,我的数据库中有这个表,我想在wabpage上填充数据 parent_topic child_topic 4 5 4 6 4 7 5 8 5 9 5 11 5 11 5 13 12
parent_topic child_topic
4 5
4 6
4 7
5 8
5 9
5 11
5 11
5 13
12 14
13 15
8 16
8 17
8 18
16 19
9 20
20 21
9 22
9 23
6 24
25 25
24 26
6 27
24 25
25 21
我正在研究python。我应该使用什么算法来填充此表。
格式如下所示
- 主话题1(没有任何家长的话题)
- 子话题
- 子话题
- 子话题
- 子话题
- 子话题
- 子话题
- 主要议题2
- 子话题
我试图使用嵌套字典,但无法创建这样的字典
提前谢谢 很抱歉我的伪Python:) 假设您使用返回主题行的方法get_lines()列出了对象的主题:
def PrintTopic(topic, margin):
for line in topics[topic].get_lines():
print " " * margin + line
def PrintRecursiveTopic(db, currentTopic, depth):
PrintTopic(currentTopic, depth)
for topic in db.topics.where(lambda x: x.parent_topic == currentTopic):
PrintRecursiveTopic(db, topic.child_topic, depth + 1)
深度是PrintTopic用边距打印的我强烈建议您阅读此博客 该博客详细介绍了工业上使用的两种主要方法,即邻接列表模型和改进的前序树遍历算法 邻接列表模型方法就是数据库使用的方法。通过从顶部节点递归来迭代树。在许多情况下,人们不希望或无法将所有数据加载到内存中,因此每个节点上的迭代都会筛选出一个新的SQL查询。这是邻接列表方法的最大缺点 是一个基于Django框架的邻接列表实现高效树实现的库。虽然您可能不使用django,但您仍然可以从django中学到很多东西 当对树的读取数大于对树的更改数时(对于网站通常如此),改进的预排序树遍历算法更有效,因此它比 邻接列表方法
django的改进的前序树遍历算法也有一个很好的实现:递归方法
list_pc = [
(4,5),
(4,6),
(4,7),
(5,8),
(5,9),
(5,11),
(5,11),
(5,13),
(12,14),
(13,15),
(8,16),
(8,17),
(8,18),
(16,19),
(9,20),
(20,21),
(9,22),
(9,23),
(6,24),
(24,25),
(24,26),
(6,27),
(24,25),
(25,21),
]
dict_pc = {}
parents = set()
children = set()
for p, c in list_pc:
parents.add(p)
children.add(c)
dict_pc.setdefault(p, []).append(c)
roots = sorted(list(parents - children))
def print_tree(level, p):
global dict_pc
print '.'*level, p
for c in dict_pc.get(p, []):
print_tree(level + 1, c)
for r in roots:
print_tree(0, r)
输出:
4
. 5
.. 8
... 16
.... 19
... 17
... 18
.. 9
... 20
.... 21
... 22
... 23
.. 11
.. 11
.. 13
... 15
. 6
.. 24
... 25
.... 21
... 26
... 25
.... 21
.. 27
. 7
12
. 14
这只是一个建议,取决于您的数据库,您可以直接使用sql命令来执行此操作。我将使用递归算法…“25”是其本身的父项???不,唐!这显然是个错误。。。sry!!如何找到顶级主题?我想我们都知道。在另一种情况下,我们可以从任何一个主题重复调用其父主题,直到父主题不等于子主题。我不认为博客引入了这些方法,因为它们在博客开始之前就已经存在了。@Juliusz抱歉,我误解了这个词。英语不是我的母语。