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

Python递归函数匹配条件成功时如何正确返回parent_id值

实现方案

你只需要把递归调用的返回值逐层传递即可,不需要额外使用break语句,return会直接终止当前函数的所有循环逻辑,自动跳出所有遍历。

修改后的代码如下:

def rep_func(parent_id, account_id):
    ...

    for page in iterator:
        for item in page['Children']:
            # 注意原代码里的id变量请确认是否为传入的account_id,避免匹配逻辑出错
            if id == item['Id']:
                return parent_id
                
    for page in org_iterator:
        for ou in page['Children']:
            # 接收递归返回结果
            match_res = rep_func(ou['Id'], account_id)
            # 下层递归已经找到匹配项,直接向上传递结果,终止当前层遍历
            if match_res is not None:
                return match_res
    # 全链路未匹配到目标,返回空标识
    return None

逻辑说明

  • 当内层匹配到目标Id时,直接return parent_id终止当前层函数,将结果返回给上层调用处
  • 上层调用接收到非空的返回值时,说明已经找到目标,不需要继续遍历剩余的OU,直接再次return把结果向上传递,直到返回给最开始的调用方
  • return本身会终止当前函数的所有循环,不需要额外加break语句

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 02:24:01