I want to create a N-ary tree in which each node will contain a key(name) and a value.
1 root then N children with two fields = name and associate value and again each children have N-children with 2 fields.
looking for simpler approach without using class using only dictionary and lists (if possible??).
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': []}]}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.