递归函数在Python中返回none 我有这段代码,出于某种原因,当我尝试返回路径时,我得到的是:def get_path(dictionary, rqfile, prefix=[]):for filename in dictionary.keys():
path = prefix+[filename]
if not isinstance(dictionary[filename], dict):
if rqfile in str(os.path.join(*path)):
return str(os.path.join(*path))
else:
get_path(directory[filename], rqfile, path)有办法解决这个问题吗?提前致谢。
2 回答

凤凰求蛊
TA贡献1825条经验 获得超4个赞
您需要返回递归结果:
else: return get_path(directory[filename], rqfile, path)
否则函数只是在执行该语句后结束,导致None
返回。
你可能要下降了else:
,总是返回结尾:
for filename in dictionary.keys(): path = prefix+[filename] if not isinstance(dictionary[filename], dict): if rqfile in str(os.path.join(*path)): return str(os.path.join(*path)) return get_path(directory[filename], rqfile, path)
因为如果rqfile in str(os.path.join(*path))
是,False
那么你没有那么好结束你的功能return
。如果在这种情况下None
递归不是正确的选项,但返回不是,则还需要处理该edgecase。

qq_花开花谢_0
TA贡献1835条经验 获得超7个赞
虽然我认为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/150
提交
取消