递归函数在Python中不返回任何内容

递归函数在Python中不返回任何内容

问题描述:

我有这段代码,由于某种原因,当我尝试返回路径时,我得到 None :

I have this piece of code, for some reason when I try to return the path, I get None instead:

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)

有没有办法解决这个问题?提前致谢.

Is there a way to solve this? Thanks in advance.

需要返回递归结果:

else:
   return get_path(directory[filename], rqfile, path)

否则函数会在执行该语句后简单地结束,导致返回 None.

otherwise the function simply ends after executing that statement, resulting in None being returned.

您可能希望删除else:并始终在最后返回:

You probably want to drop the else: and always return at the end:

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 那么你结束你的函数没有 返回代码>也是如此.如果在这种情况下递归不是正确的选择,但返回 None 不是正确的选择,那么您也需要处理该边缘情况.

because if rqfile in str(os.path.join(*path)) is False then you end your function without a return as well. If recursing in that case is not the right option, but returning None is not, you need to handle that edgecase too.