Python 中递归函数不返回任何值[重复]
- 2024-12-25 08:51:00
- admin 原创
- 146
问题描述:
我有这段代码,由于某种原因,当我尝试返回路径时,我得到的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)
有办法解决这个问题吗?
解决方案 1:
您需要返回递归结果:
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
,那么您也会在不带 a 的情况下结束函数return
。如果在这种情况下递归不是正确的选择,但返回None
又不是正确的选择,那么您也需要处理这种极端情况。
解决方案 2:
虽然我认为 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"))
egh
>>> print(get_path(directory, r'gh'))
egh
如果您不想在找不到文件时引发异常,您也可以返回一个哨兵值来代替None
最后一行,并在递归情况下检查哨兵值而不是try
/ except
:
result = get_path(value, rqfile, path)
if result is not None:
return result
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD