[英]N-ary tree in python
I want to create a N-ary tree in which each node will contain a key(name) and a value.我想创建一个 N 叉树,其中每个节点都包含一个键(名称)和一个值。
1 root then N children with two fields = name and associate value and again each children have N-children with 2 fields. 1 个根,然后是 N 个孩子,有两个字段 = 名称和关联值,每个孩子都有 N 个孩子,有 2 个字段。
looking for simpler approach without using class using only dictionary and lists (if possible??).寻找更简单的方法而不使用 class 仅使用字典和列表(如果可能的话??)。
class Node():
#Do something
# ....
class Node(object):
def __init__(self, name, value):
self.name = name
self.value = value
self.children = []
def add_child(self, obj):
self.children.append(obj)
You say youre looking for a "simpler approach without using class" but my claim here is that 9 times out of 10 using a class for this will be the simpler approach. 您说您正在寻找一种“不使用类的简单方法”,但是我的主张是,使用类的十分之九的方法将是更简单的方法。
If you insist on not using classes:如果你坚持不使用类:
def create_node(name, value):
return {
'name': name,
'value': value,
'children': []
}
def add_child(node, obj):
node['children'].append(obj)
########################################
node = create_node('foo', 0)
add_child(node, create_node('bar', 1))
print(node)
# Result: {'name': 'foo', 'value': 0, 'children': [{'name': 'bar', 'value': 1, 'children': []}]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.