分层排序数据

dte*_*lus 2 python sorting list set hierarchical-data

我的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} }
Run Code Online (Sandbox Code Playgroud)

在每个子列表中,数据都是这样构造的{*article_id*, *parent_id*} 如果 article_id 和 parent_id 相同,这显然意味着文章没有父级。

我想使用最少的代码对数据进行排序,以便对于每篇文章,如果可用,我可以轻松访问它的子项和孙项(嵌套数据)的列表。例如(使用上面的示例数据)我应该能够在一天结束时打印:

 1
 -45
 --566
 ---783
 -66
 --911
Run Code Online (Sandbox Code Playgroud)

.... 文章编号 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)
Run Code Online (Sandbox Code Playgroud)

遗憾的是,我的代码不起作用。

任何朝着正确方向的帮助/推动将不胜感激。谢谢

大卫

Hyp*_*eus 5

也许是这样的:

#! /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 ()
Run Code Online (Sandbox Code Playgroud)

这将创建一个树结构,您可以遍历该结构以获取所有子项。您可以通过 访问任何文章并通过t.nodes [article]获取其子项t.nodes [article].children

打印方法的输出是:

1
    45
        566
            783
    66
        911
4
    22
        80
    8
        300
7
    101
17
Run Code Online (Sandbox Code Playgroud)