我将从fatherson字典(python)开始创建一个树结构

2024-04-20 03:10:12 发布

您现在位置:Python中文网/ 问答频道 /正文


{'6690': [6620, 3618, 5547, 6660],
   '6620': [6303, 5199, 6293, 6597],
   '3618': [3616],
   '5547': [4137],
   '6660': [6621, 4138, 3558, 3556]

早上好,我有一个像上面显示的数据结构。 我想从这个结构开始创建一个表示父子层次结构的树结构。 例如:


6690
--- 6620
---- 6303
---- 5199
---- 6293
---- 6597
--3618
---- 3616
--5574
---- 4137
--- 6660
---- 6621
---- 4138
---- 3558
---- 3556

如何在python中运行它


2条回答

您可以创建一个树数据结构,然后以深度优先的方式打印

d = {'6690': [6620, 3618, 5547, 6660],
   '6620': [6303, 5199, 6293, 6597],
   '3618': [3616],
   '5547': [4137],
   '6660': [6621, 4138, 3558, 3556]
    }

class Node:
    def __init__(self, val=None, children=None):
        self.children = [] if children is None else children
        self.val = val
        
class Tree:
    def __init__(self):
        self.root = None
        self.map = {}
        
    def depth_first_print(self, node=None, depth=0):
        node = self.root if node is None else node
        print(' '*depth, node.val)
        for each_children in node.children:
            self.depth_first_print(each_children, depth+1)
            

nodes = set(map(str, {j for i in d.values() for j in i}.union(set(d.keys()))))

t = Tree()
for each_node in nodes:
    t.map[each_node] = Node(val=each_node)
    
t.root = t.map['6690']

for k, v in d.items():
    for each_child in v:
        t.map[str(k)].children.append(t.map[str(each_child)])
        
        
t.depth_first_print()

#  6690
#   6620
#    6303
#    5199
#    6293
#    6597
#   3618
#    3616
#   5547
#    4137
#   6660
#    6621
#    4138
#    3558
#    3556

假设第一个字典条目的键是最古老的祖先

然后

  1. 必须首先定义一个节点
  2. 递归地构建树
father_son = {'6690': [6620, 3618, 5547, 6660],
   '6620': [6303, 5199, 6293, 6597],
   '3618': [3616],
   '5547': [4137],
   '6660': [6621, 4138, 3558, 3556]}

# 1) arbitrary node definition
class Node:
    def __init__(self, value, children):
        self.value = value
        self.children = children

# 2) building tree recursively
def build_tree(parent):
    node = Node(parent, [])
    
    if parent in father_son:
        for child in father_son[parent]:
            node.children.append(build_tree(child))
    
    return node


# 3) call the above function to build tree

oldest = next(iter(father_son.keys()))  # returns 6690 in this example
root = build_tree(oldest)

相关问题 更多 >