如果存在则获取子节点,否则在Python中创建

时间:2016-11-03 14:30:04

标签: python

我有一个基本类,包含两个属性'Name'和'Children。

region

我有一个核心根节点,如下所示:

class Node():
    def __init__(self, name):
        self.name = name
        self.children = []

我如何创建一个可以将路径传递给树中特定节点的函数,并且函数返回该节点。 但是,如果该节点不存在,它将创建/附加到树,并仍然返回节点。

# Create Master Root Node
root = Node('root')

如果路径在到达路径末尾之前失败,它将自动创建缺失的节点,以使整个路径完成。

enter image description here

path = ['Leslie','Marie','Tori'] # simple example

def get_node_by_path(path=[])...

enter image description here

3 个答案:

答案 0 :(得分:1)

我做这样的事情。它是一种非递归解决方案。

def get_node_by_path(path):
    cur_node = root
    for elem_name in path:
        found = False
        for child in cur_node.children:
            if child.name == elem_name:
                cur_node = child
                found = True
                break
        if not found:
            new_node = Node(elem_name)
            cur_node.children.append(new_node)
            cur_node = new_node
    return cur_node

答案 1 :(得分:-1)

class Node:
    def __init__(self, name):
        self.name = name
        self.children = []

    def path_to(self, path):
        if not path:
            return self
        head, *tail = path
        for child in self.children:
            if child.name == head:
                return child.path_to(tail)
        newborn = Node(head)
        self.children.append(newborn)
        return newborn.path_to(tail)

这是一个递归地考虑列表中的第一个名称是否是当前节点的子名称的解决方案。

对于Python 2,head, *tail = path可以替换为

head = path[0]
tail = path[1:]

答案 2 :(得分:-1)

从最后一个dag对象开始,然后转到根

class Node():
    def __init__(self, name = "", childern = []):
        self.name = name
        self.children = childern
        print ("Node Name: {0} Childern Nodes {1}".format(self.name, self.children))

def get_node_by_path(path=[]):
    for c,n in enumerate(reversed(path)):
        if not c:
            Node(name = n)
        else:
            Node(name = n, childern = path[-c:])

path = ['root', 'Leslie','Marie','Tori','Kevin']
get_node_by_path(path)