Python基于给定数组/列表构建树形结构并查询子节点所有父节点
树形结构构建与查询实现
方案1:固定4层嵌套字典结构(匹配你给出的输出格式)
输入为4个对应列的独立列表,先将其按行拼接为四元组,再逐层构建嵌套字典:
# 输入示例:4个对应列的列表 p_list = ['P1', 'P1', 'P1', 'P1', 'P2', 'P2', 'P2'] l_list = ['L1', 'L1', 'L1', 'L1', 'L1', 'L2', 'L3'] v_list = ['V1', 'V1', 'V2', 'V3', 'V2', 'V1', 'V4'] o_list = ['O1', 'O2', 'O1', 'O3', 'O1', 'O2', 'O2'] def build_four_layer_tree(p_list, l_list, v_list, o_list): tree = {} # 按行拼接四元组 rows = zip(p_list, l_list, v_list, o_list) for p, l, v, o in rows: # 逐层创建节点,不存在则初始化 if p not in tree: tree[p] = {} if l not in tree[p]: tree[p][l] = {} if v not in tree[p][l]: tree[p][l][v] = {} tree[p][l][v][o] = o return tree # 调用生成树 tree = build_four_layer_tree(p_list, l_list, v_list, o_list)
输出结构与你要求的字典格式完全一致。如果需要打印成带|的可视化树形文本,可以配合如下打印函数使用:
def print_tree(node, indent=0): for key, value in node.items(): print(" " * indent + f"|{key}") if isinstance(value, dict): print_tree(value, indent + 1)
方案2:带反向索引的优化方案(更适配父节点查询需求)
你的核心需求是查询最底层节点的所有父节点,额外新增反向索引可以实现O(1)复杂度的查询,不需要遍历整棵树:
def build_tree_with_index(p_list, l_list, v_list, o_list): tree = {} # 反向索引:key为最底层O节点,value为对应父节点列表 [P, L, V] # 若存在相同O对应多路径的场景,可将value改为列表存储所有路径 reverse_index = {} rows = zip(p_list, l_list, v_list, o_list) for p, l, v, o in rows: if p not in tree: tree[p] = {} if l not in tree[p]: tree[p][l] = {} if v not in tree[p][l]: tree[p][l][v] = {} tree[p][l][v][o] = o reverse_index[o] = [p, l, v] return tree, reverse_index # 查询示例:获取O1的所有父节点 tree, reverse_index = build_tree_with_index(p_list, l_list, v_list, o_list) print(reverse_index.get('O1', []))
通用层级适配版本
如果输入的层级数量不固定(不一定是4层),可以使用如下通用版本,自动适配任意层数的输入:
def build_generic_tree(rows): tree = {} reverse_index = {} for row in rows: current = tree # 自动拆分父层级与底层节点 *parent_nodes, leaf_node = row for node in parent_nodes: if node not in current: current[node] = {} current = current[node] current[leaf_node] = leaf_node reverse_index[leaf_node] = parent_nodes return tree, reverse_index # 调用示例:任意层数的行输入 rows = [ ('P1', 'L1', 'V1', 'O1'), ('P1', 'L1', 'V1', 'O2'), ('P2', 'L3', 'V4', 'O2') ] tree, reverse_index = build_generic_tree(rows)
内容的提问来源于stack exchange,提问作者Andrea T
相关产品推荐
相关产品推荐

