python函数从单个路径字符串获取无限级的子路径

cedebl8k  于 2023-03-31  发布在  Python
关注(0)|答案(2)|浏览(120)

嗨,我被困在一个程序逻辑是我从第三方的API像路径

paths = ['path1' , 'path2']

现在我必须得到两个的孩子。API将返回每一次只是一步,例如,如果我将传递一个路径给它

result = get_path_from_api(path='path1')

它会导致

paths = ['path1/subpath1' , 'path1/subpath2']

现在的情况是,当我从get_path_from_api调用中获得[]时,我将停止。并且我必须进一步甚至找到['path1/subpath1' , 'path1/subpath2']的所有子路径,并最终合并到单个数组中。
现在我的功能是

def get_subpaths(path_name):
    sub_paths = []
    print(path_name, "path_name")
    paths = get_path_from_api(path=path_name)
    for path in paths:
        if path.is_directory:
            sub_paths.append(path.name)
        sub_path_final = []
        while sub_path_final != None:
            sub_path_final = get_subpaths(path.name)
    return sub_paths if sub_paths else None

任何帮助都将不胜感激。
最终预期结果

final = ['path1' , 'path1/subpath1' , 'path1/subpath2' , 'path2' , 'path2/subpath2' , 'path2/subpath2' , 'path3/subpath3']
zdwk9cvp

zdwk9cvp1#

比起使用递归,使用队列和while循环可能更容易,这样你就不必传递大量的容器,也不必担心调用堆栈的大小。

def get_subpaths(path_name):
    results = []
    search_queue = {path_name}

    while search_queue:
        search_path = search_queue.pop()
        results.append(search_path)
        print(f"{search_path=}")

        for path in get_path_from_api(path=search_path):
            if path.is_directory:
                search_queue.add(path.name)

    return results
zengzsys

zengzsys2#

from queue import deque

simulated_filesystem = {
        '': ['path1', 'path2', 'path3'],
        'path1': ['path1/subpath1', 'path1/subpath2'],
        'path2': ['path2/subpath1', 'path2/subpath2'],
        'path3': ['path3/subpath3'],
}

class ApiPathObject:
    def __init__(self, name):
        self.is_directory = True
        self.name = name
    def __repr__(self):
        return f"{self.name}"

def get_path_from_api(path) -> list[ApiPathObject]:
    return [ApiPathObject(name) for name in simulated_filesystem.get(path, [])]

def get_subpaths_bfs(path_name):
    """ generator, breadth first search, using a python list as a stack """
    paths = [path_name]
    while paths:
        for path in get_path_from_api(paths.pop()):
            if path.is_directory:
                paths.append(path.name)
                yield path.name

def get_subpaths_dfs(path_name):
    """ generator, depth first search, preorder """
    paths = deque(get_path_from_api(path_name))
    while paths:
        path = paths.popleft()
        if path.is_directory:
            yield path.name
            for subpath in reversed(get_path_from_api(path.name)):
                paths.appendleft(subpath)

def get_subpaths(path_name):
    return list(get_subpaths_dfs(path_name))

print(get_subpaths(''))
print(get_subpaths('path1'))
print(get_subpaths('path2'))

['path1','path1/subpath1','path1/subpath2',' path2','path2/subpath1','path2/subpath2','path3','path3/subpath3']
[“路径1/子路径1”,“路径1/子路径2”]
[“路径2/子路径1”,“路径2/子路径2”]

相关问题