通过目录结构进行递归搜索

时间:2018-08-10 13:05:43

标签: python-3.x

我创建了用于使用data查找目录的递归函数,

ID

在此目录结构上运行测试(def find_id(content, id): for drive_obj in content: print('Got {}'.format(drive_obj.id)) if drive_obj.id == id: print('Find id in {}'.format(drive_obj.id)) return drive_obj elif type(drive_obj) == Directory and drive_obj.children: print('{} has children'.format(drive_obj.id)) return find_id(drive_obj.children, id) )后:

find_id(example_structure, 'c')

我遇到了问题,因为使用dir_a -----dir_b ----------file_e -----dir_c -----dir_d dir_f Logs: Got a a has children Got b b has children Got e 查找文件后的功能不会检查下一个id = e。它只是返回dir_c而不是继续循环。我的函数或对函数/递归函数的理解完全不对吗?

1 个答案:

答案 0 :(得分:1)

问题是因为即使没有找到您要查找的目录,您也return find_id(drive_obj.children, id)

def find_id(content, id):
    for drive_obj in content:
        print('Got {}'.format(drive_obj.id))
        if drive_obj.id == id:
            print('Find id in {}'.format(drive_obj.id))
            return drive_obj
        elif type(drive_obj) == Directory and drive_obj.children:
            print('{} has children'.format(drive_obj.id))
            result = find_id(drive_obj.children, id)  # Now if find_id returns None, we don't stop
            if result:  # result is not None if your objects can be falsy
                return result

您希望find_id在找不到任何内容的情况下返回None,并且希望避免将这些None的结果冒泡给调用者。