我有这段代码,由于某种原因,当我尝试返回路径时,我得到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
递归不是正确的选择,而在返回则不是正确的选择,那么您也需要处理这种边缘情况。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句