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
相关产品推荐
相关产品推荐

