递归函数在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)
有办法解决吗?提前致谢。
-
你需要返回递归结果:
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递归不是正确的选择,而在返回则不是正确的选择,那么你也需要处理这种边缘情况。