You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python递归生成子-父层级结构时遇类型错误求助

问题分析与解决方案

报错原因

你写的hierarchy_gen函数报错是因为调用hierarchy_gen(c_p[last_parent])时,c_p[last_parent]返回的是字符串(比如c_p["C"]的值是"F"),但函数逻辑里执行了data.copy()——字符串类型没有copy方法,因此触发了'str' object has no attribute 'copy'错误。

你的递归思路方向错了:函数接收的是整个字典,但递归时却传入了单个父节点的字符串值,类型不匹配导致报错。

正确实现方式

我们不需要把整个字典递归传递,而是针对每个节点单独向上遍历父链,直到遇到终止条件(空字符串或指定节点)。以下提供两种简洁的实现方式:

方式1:迭代遍历(推荐,避免递归深度问题)

直接遍历每个节点,从直接父节点开始,不断通过c_p向上查找祖辈,直到符合终止条件:

c_p = { "A":"C","B":"C","C":"F","D":"E","E":"F","F":""}
hierarchy = {
    "A": ["C"],
    "B": ["C"],
    "C": ["F"],
    "D": ["E"],
    "E": ["F"],
    "F": [""],
}
expected_result = {
    "A": ["C", "F"],
    "B": ["C", "F"],
    "C": ["F"],
    "D": ["E", "F"],
    "E": ["F"],
    "F": [""],
}

def hierarchy_gen(hierarchy_dict, parent_map):
    # 复制原字典避免修改原始数据
    result = {k: v.copy() for k, v in hierarchy_dict.items()}
    for node, ancestors in result.items():
        current_parent = ancestors[-1]
        # 循环向上找父节点,直到遇到空字符串或F
        while current_parent not in ['', 'F']:
            next_parent = parent_map[current_parent]
            ancestors.append(next_parent)
            current_parent = next_parent
    return result

test = hierarchy_gen(hierarchy, c_p)
print(test == expected_result)  # 输出True

方式2:递归生成单节点父链

先写一个递归函数生成单个节点的完整父链,再批量构建最终的层级字典:

def get_full_parent_chain(node, parent_map):
    parent = parent_map[node]
    # 终止条件:父节点为空字符串
    if parent == '':
        return [""] if node == "F" else []
    # 递归拼接父节点和祖辈链
    return [parent] + get_full_parent_chain(parent, parent_map)

# 构建最终层级字典
new_hierarchy = {node: get_full_parent_chain(node, c_p) for node in c_p}
print(new_hierarchy == expected_result)  # 输出True

这两种方式都能正确生成你需要的完整层级链,且不会出现类型错误。

内容的提问来源于stack exchange,提问作者Rizakha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 13:40:24