在python中循环遍历树层次结构? [英] Looping through tree hierarchy in python?

查看:70
本文介绍了在python中循环遍历树层次结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的,对 Python 非常陌生!

I'm new here and pretty new to python!

我们完成了作业,我已经能够完成剩下的作业,但仍然存在一个问题:如果我有这样的树层次结构:

We got a homework, and I already was able to do rest of it, but one problem remains: If I have a tree hierarchy like this:

root = [
    parent1 = [
        child1,
        child2 = [
            sub_child
        ]
        child3
    ],
    parent2 = [
        child1,
        child2
    ]
]

而且它们都是一个名为TreeHierarchyClass的类的实例,而且它们都有一个名称属性,我如何找到输入名称的那个?

And they are all instances of one class named TreeHierarchyClass, and they all have a name attribute, how can I find the one with name I input?

我尝试使用 for 循环,但无法知道我需要多少个循环?取名字很容易:

I tried to use for loops but there's no way to know how many I need? Getting the name is easy:

name = input("Enter name: ")
if name == TreeHierarchyObject.name:
    print("Found it!")

但是我如何遍历对象?

推荐答案

你应该在这里使用简单的递归.该方法在一定程度上取决于您的子对象如何附加到父对象.

You should use simple recursion here. The method depends a little on how your child objects are attached to the parent object.

如果它们在列表 self.children 中,则此方法有效,我建议这样做.只需在您的类中定义以下方法:

This one works if they are in a list self.children, which I'd recommend to do. Just define the following method inside your class:

def findObjectByName(self, name):
    if self.name == name:
        return self
    else:
        for child in self.children:
            match = child.findObjectByName(name)
            if match:
                return match

要使其适用于任何属性,而不仅仅是名称,请改用 getattr():

To make this work for any attribute, not just name, use getattr() instead:

def findObject(self, attr, value):
    if getattr(self, attr) == value:
        return self
    else:
        for child in self.children:
            match = child.findObject(attr, value)
            if match:
                return match

只需调用 root.findObjectByName("Sub Child!") 或使用第二种方法:root.findObject("name", "Sub Child!")

And simply call root.findObjectByName("Sub Child!") or to use the second method: root.findObject("name", "Sub Child!")

这篇关于在python中循环遍历树层次结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆