Python - 没有 类 的树
Python - Tree without classes
如何在不使用 python 中的 类 的情况下实现树?我只能使用列表、字典和队列。显然没有库 bintree.
我一般用defaultdict
:
from collections import defaultdict
def Tree():
return defaultdict(Tree)
用法:
>>> records = Tree()
>>> records['Artist']['Maria Callas']['Song']['O Mio Babbino Caro']['Year'] = 1965
奖金:玛丽亚卡拉斯唱歌O Mio Babbino Caro
您可以使用
{'value': None, 'nodes': []}
代表每个节点。
例如:
可以表示为:
{'value': '+', 'nodes':
[
{'value': '2', 'nodes': []},
{'value': '*', 'nodes':
[
{'value': '3', 'nodes': []},
{'value': '5', 'nodes': []}
]
}
]
}
注意:仅用于教育目的。已经实现了更高效的数据结构。
如何在不使用 python 中的 类 的情况下实现树?我只能使用列表、字典和队列。显然没有库 bintree.
我一般用defaultdict
:
from collections import defaultdict
def Tree():
return defaultdict(Tree)
用法:
>>> records = Tree()
>>> records['Artist']['Maria Callas']['Song']['O Mio Babbino Caro']['Year'] = 1965
奖金:玛丽亚卡拉斯唱歌O Mio Babbino Caro
您可以使用
{'value': None, 'nodes': []}
代表每个节点。
例如:
可以表示为:
{'value': '+', 'nodes':
[
{'value': '2', 'nodes': []},
{'value': '*', 'nodes':
[
{'value': '3', 'nodes': []},
{'value': '5', 'nodes': []}
]
}
]
}
注意:仅用于教育目的。已经实现了更高效的数据结构。