我有一个可以从所有键值输出所有可能路径的python词典.这里有一个小规模的例子来可视化我正在try 做的事情.

字典={‘父母’:[‘子元素1’,‘子元素2’],‘子元素1’:[‘子元素1_1’,‘子元素1_2’],‘子元素2’:[‘子元素2_1’,‘子元素2_2’],‘子元素3’:[],‘子元素1_1’=[‘子元素1_1’,‘子元素1_2’],‘子元素1_1_1’:[],‘子元素1_1_2’:[],‘子元素1_2’:[],‘子元素1_2’:[],‘子元素2_1’:[],‘子元素2_2’:[],‘子元素4’=[]}

我想要的输出是这样的:

家长/子元素1

家长/子元素1/child1_1

家长/子元素1/child1_1/child1_1_1

家长/子元素1/child1_1/child1_1_2

家长/子元素1/child1_2

父母/子元素2/子元素2_1

父母/子元素2/子元素2_2

家长/子元素3

家长/子元素4

.

.

.

Please note that I'd like to use it for a larger scale, so using 2 for loops I was able to output a path with parent and a 2 direct childs of it. But it doesn't work on larger scale, I think I need a for loop inside of a while true loop where I can check if a child doesn't have any childs of itself and it outputs me “Hey I'm the last one left and here is paths that are available to me" etc.

Thanks in advance and have a nice day.

推荐答案

父代中没有提到子代3和子代4,那么,如果我们忽略为您提供所需输出的函数是这样的,您希望如何在输出中指向父代:

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

Python相关问答推荐

try 从网站获取表(ValueRight:如果使用所有纯量值,则必须传递索引)

如何推迟对没有公钥的视图/表的反射?

如何从维基百科的摘要部分/链接列表中抓取链接?

拆分pandas列并创建包含这些拆分值计数的新列

具有症状的分段函数:如何仅针对某些输入值定义函数?

计算所有前面行(当前行)中列的值

Python中MongoDB的BSON时间戳

可变参数数量的重载类型(args或kwargs)

Excel图表-使用openpyxl更改水平轴与Y轴相交的位置(Python)

将图像拖到另一个图像

在Mac上安装ipython

修复mypy错误-赋值中的类型不兼容(表达式具有类型xxx,变量具有类型yyy)

无法使用DBFS File API路径附加到CSV In Datricks(OSError Errno 95操作不支持)

cv2.matchTemplate函数匹配失败

如果满足某些条件,则用另一个数据帧列中的值填充空数据帧或数组

CommandeError:模块numba没有属性generated_jit''''

Python—为什么我的代码返回一个TypeError

ModuleNotFoundError:没有模块名为x时try 运行我的代码''

当条件满足时停止ODE集成?

Odoo16:模板中使用的docs变量在哪里定义?