[英]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.