简体   繁体   English

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

[英]Get child node if exists otherwise create in Python

I have a basic class containing two attributes 'Name' and 'Children. 我有一个包含两个属性“名称”和“子级”的基本类。

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

I have a core root node as follows: 我有一个核心根节点,如下所示:

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

How would I go about creating a function that I could pass a path to a specific node in the tree, and the function return that node. 我将如何创建可以传递路径到树中特定节点的函数,然后该函数返回该节点。 However if that node doesn't exist it would create/append to the tree, and still return the node. 但是,如果该节点不存在,它将创建/追加到树上,并仍然返回该节点。

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

def get_node_by_path(path=[])...

If a path failed before reaching the end of the path, it would automatically create the missing nodes in order to make the entire path complete. 如果路径在到达路径末尾之前发生故障,它将自动创建丢失的节点,以使整个路径完整。

在此处输入图片说明

path = ['Leslie','Marie','Tori','Kevin'] # more complex requires two nodes to be created

def get_node_by_path(path=[])...

在此处输入图片说明

I'd do something like this. 我会做这样的事情。 It's a non recursive solution. 这是一个非递归的解决方案。

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
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)

Here's a solution that recursively considers whether the first name in the list is a child of the current node. 这是一个递归考虑列表中名字是否是当前节点的子代的解决方案。

For Python 2, head, *tail = path can be replaced with 对于Python 2, head, *tail = path可以替换为

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

start with the last dag object and go to the root 从最后一个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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python将数据框写入Excel-检查选项卡是否存在并覆盖,否则创建 - Python writing dataframe to excel - Check if tab exists and overwrite otherwise create 在XML python中获取子节点 - Get Child node in XML python Python,如果存在则打开写入,否则会引发错误 - Python, open for writing if exists, otherwise raise error 如果存在新的子节点,如何在每次迭代中使用 python 将 append 到 JSON 中的子节点? - How to append to the child node in JSON at every iteration using python provided new child node exists? 检查现有进程是否存在 - 如果存在,则与其通信,否则创建一个新进程 - Check if existing process exists - if it does, communicate with it, otherwise create a new one 使用子节点lxml python获取父节点 - Get parent node using child node lxml python 如何使用python获取父节点下的子节点的索引? - how to get the index of a child node under a parent node using python? 如果标签存在,则获取标签的属性; 否则无 - Get tag's attribute if tag exists; otherwise None 如果在拆分后存在,则提取(获取)第二个字符串,否则首先 - Extracting (get) second string if exists after splitting, otherwise first 获取当前的python模块对象(按名称或其他方式) - Get current python module object (by name or otherwise)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM