我的 python 程序返回一个包含子列表数据的列表。每个子列表包含文章的唯一 ID 和该文章的父 ID,即
pages_id_list ={ {22, 4},{45,1},{1,1}, {4,4},{566,45},{7,7},{783,566}, {66,1},{300,8},{8,4},{101,7},{80,22}, {17,17},{911,66} }
在每个子列表中,数据都是这样构造的 {*article_id*, *parent_id*}
如果 article_id 和 parent_id 相同,则显然意味着该文章没有父级。
我想使用最少的代码对数据进行排序,这样对于每篇文章,我都可以轻松 如果可用,访问它的子孙列表(嵌套数据)。例如(使用上面的示例数据)我应该能够在一天结束时打印:
1
-45
--566
---783
-66
--911
.... 对于文章 id 1
我只能整理出最高级别(第一代和第二代)的ID。在获取第 3 代和后续代时遇到问题。
这是我使用的代码:
highest_level = set()
first_level = set()
sub_level = set()
for i in pages_id_list:
id,pid = i['id'],i['pid']
if id == pid:
#Pages of the highest hierarchy
highest_level.add(id)
for i in pages_id_list:
id,pid = i['id'],i['pid']
if id != pid :
if pid in highest_level:
#First child pages
first_level.add(id)
else:
sub_level.add(id)
很遗憾,我的代码不起作用。
在正确方向上的任何帮助/插入将不胜感激。 谢谢
大卫
最佳答案
也许是这样的:
#! /usr/bin/python3.2
pages_id_list = [ (22, 4),(45,1),(1,1), (4,4),(566,45),(7,7),(783,566), (66,1),(300,8),(8,4),(101,7),(80,22), (17,17),(911,66) ]
class Node:
def __init__ (self, article):
self.article = article
self.children = []
self.parent = None
def print (self, level = 0):
print ('{}{}'.format ('\t' * level, self.article) )
for child in self.children: child.print (level + 1)
class Tree:
def __init__ (self): self.nodes = {}
def push (self, item):
article, parent = item
if parent not in self.nodes: self.nodes [parent] = Node (parent)
if article not in self.nodes: self.nodes [article] = Node (article)
if parent == article: return
self.nodes [article].parent = self.nodes [parent]
self.nodes [parent].children.append (self.nodes [article] )
@property
def roots (self): return (x for x in self.nodes.values () if not x.parent)
t = Tree ()
for i in pages_id_list: t.push (i)
for node in t.roots: node.print ()
这将创建一个树结构,您可以遍历该结构以获取所有子项。您可以通过 t.nodes [article]
访问任何文章,并通过 t.nodes [article].children
获取其子项。
打印方法的输出是:
1
45
566
783
66
911
4
22
80
8
300
7
101
17
关于python - 分层排序数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14189114/