我有一个Python词典,我想从所有钥匙值中输出所有可能的路径。这是一个小规模的示例,可视化我要做的事情。

dictionary = {'parent':['child1','child2'],'child1':['child1_1','child1_2'],'child2':['child2_1','child2_2'],'child2_2'],'child3':[[ ],'child1_1'= ['child1_1_1','child1_1_2'],'child1_1_1':[],'child1_1_2':[],'child1_2':[],'child2_1':[],'child2_2'':[] ,'child4'= []}

我想拥有的输出就是这样:

parent/child1

parent/child1/child1_1

parent/child1/child1_1/child1_1_1

parent/child1/child1_1/child1_1_2

parent/child1/child1_2

parent/child2/child2_1

parent/child2/child2_2

parent/child3

parent/child4

请注意,我想将其用于更大的规模,因此使用2用于循环,我能够与父母一起输出一条路径和2个直接的孩子。但这在更大的规模上不起作用,我认为我需要一个循环的循环,我可以检查一个孩子是否没有任何孩子,它会输出我:“嘿,我是最后一个左,这里是我可以使用的路径。

预先感谢,祝您有美好的一天。

分析解答

父母中未提及Child3和Child4,因此,如果我们忽略为您提供所需输出的功能,您如何指向输出中的父。

def get_paths(dictionary, parent="", paths=None):
    if paths is None:
        paths = []

    paths.append(parent)

    if parent in dictionary:
        children = dictionary[parent]
        for child in children:
            child_paths = get_paths(dictionary, child)
            paths.extend([f"{parent}/{path}" for path in child_paths])

    return paths


dictionary = {
    'parent': ['child1', 'child2'],
    'child1': ['child1_1', 'child1_2'],
    'child2': ['child2_1', 'child2_2'],
    'child3': [],
    'child1_1': ['child1_1_1', 'child1_1_2'],
    'child1_1_1': [],
    'child1_1_2': [],
    'child1_2': [],
    'child2_1': [],
    'child2_2': [],
    'child4': [],
}

paths = get_paths(dictionary, 'parent')

for path in paths:
    print(path)

输出:

parent
parent/child1
parent/child1/child1_1
parent/child1/child1_1/child1_1_1
parent/child1/child1_1/child1_1_2
parent/child1/child1_2
parent/child2
parent/child2/child2_1
parent/child2/child2_2