将扁平结构转换为树形结构:Python 实现

Python 2023-02-07

在处理数据时,我们经常需要将扁平结构(如数据库表中的数据)转换为树形结构。这种转换在许多场景中都非常有用,例如构建层级菜单、组织结构图或者文件系统。在本文中,我们将介绍如何使用 Python 将给定的扁平数据列表转换为树形结构。

首先,我们需要一个包含节点信息的列表。列表中的每个元素都应包含一个 parent_id 属性,表示其父节点。为了简化示例,我们假设列表中的元素是字典,如下所示:

source_list = [
    {'id': 1, 'name': 'A', 'parent_id': None},
    {'id': 2, 'name': 'B', 'parent_id': 1},
    {'id': 3, 'name': 'C', 'parent_id': 1},
    {'id': 4, 'name': 'D', 'parent_id': 2},
    {'id': 5, 'name': 'E', 'parent_id': 2},
    {'id': 6, 'name': 'F', 'parent_id': 3},
]

现在,我们将实现一个名为 build_tree 的函数,它将接收这个扁平列表并返回一个树形结构。

import copy

def build_tree(source_list, parent_id=None):
    tree_list = []
    for item in source_list:
        if parent_id == item['parent_id']:
            child_node = copy.deepcopy(item)
            children_nodes = build_tree(source_list, item['id'])
            if children_nodes:
                child_node['children'] = children_nodes
            tree_list.append(child_node)
    return tree_list

这个函数使用递归方法遍历源列表,查找具有给定 parent_id 的节点。对于每个匹配的节点,它创建一个新的字典(child_node),然后再次调用 build_tree 函数以查找子节点。如果找到子节点,它们将被添加到 child_node 字典中。最后,将 child_node 添加到结果列表 tree_list 中。

让我们使用上面的 source_list 示例来测试这个函数:

tree = build_tree(source_list)
print(tree)

# 输出结果将是这样的树形结构

"""
[
    {'id': 1, 'name': 'A', 'parent_id': None, 'children': [
        {'id': 2, 'name': 'B', 'parent_id': 1, 'children': [
            {'id': 4, 'name': 'D', 'parent_id': 2},
            {'id': 5, 'name': 'E', 'parent_id': 2}
        ]},
        {'id': 3, 'name': 'C', 'parent_id': 1, 'children': [
            {'id': 6, 'name': 'F', 'parent_id': 3}
        ]}
    ]}
]
"""

这个简单的函数可以在许多不同的场景中使用,例如构建嵌套菜单、显示公司组织结构或者显示论坛中的评论和回复。

希望这篇博客对你有所帮助!

感谢阅读!