python的函数is none_递归函数在Python中返回none

虽然我认为Martijn Pieters在他的回答中解决了主要问题(你需要从递归案例中返回),但我不认为他建议的代码能够正常工作。

您正在尝试对rqfile嵌套dictionary字典中的值实施深度优先搜索。但是您当前的代码无法正确处理递归情况。如果在其中一个递归调用中找到结果,或者如果递归调用未能找到目标,则需要做出相应的响应。

这是我认为你需要的东西,为了清楚起见,重命名或重新安排了一些东西:def get_path(directory, rqfile, prefix=[]):

for filename, value in directory.items():

path_list = prefix + [filename]

if not isinstance(value, dict): # base case

path = os.path.join(*path_list)

if rqfile in path:   # Found the file. Do you want to do something

return path      # with the value here, or is it junk?

else: # recursive case

try:

return get_path(value, rqfile, path_list) # this only returns if

except ValueError:                     # the recursion doesn't raise

pass

raise ValueError("Requested file not found") # not found here or in children

用法示例:>>> directory = {"a": "a info",

"b": {"c": "b/c info", "d": "b/d info"},

"e": {"f": "e/f info", "g": {"h": "e/g/h info"}}}>>> print(get_path(directory, "h"))e\g\h>>> print(get_path(directory, r'g\h'))e\g\h

如果你不想在找不到文件时引发异常,你也可以返回一个sentinel值,就像None代替最后一行一样,并在递归的情况下检查它的sentinel值而不是try/ except:result = get_path(value, rqfile, path)

if result is not None:

return result

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值