如何在Python中动态构建树 [英] How do I build a tree dynamically in Python
问题描述
Python/编程初学者的问题...我想在Python中建立树形结构,最好基于字典.我找到了能做到这一点的代码:
A beginner Python/programming question... I'd like to build a tree structure in Python, preferably based on dictionaries. I found code that does this neatly:
Tree = lambda: collections.defaultdict(Tree)
root = Tree()
这可以很容易地填充为:
This can easily be populated like:
root['toplevel']['secondlevel']['thirdlevel'] = 1
root['toplevel']['anotherLevel'] = 2
...etc.
我想动态地填充级别/叶子,以便我可以根据需要添加任意多个级别,并且叶子可以位于任何级别.我该怎么办?
I'd like to populate the levels/leaves dynamically so that I can add as many levels as needed, and where the leaves can be at any level. How do I do that?
非常感谢您的帮助.
推荐答案
您可以简单地使用实用程序功能来完成此操作
You can simply do it with a utility function, like this
def add_element(root, path, data):
reduce(lambda x, y: x[y], path[:-1], root)[path[-1]] = data
您可以像这样使用它
import collections
tree = lambda: collections.defaultdict(tree)
root = tree()
add_element(root, ['toplevel', 'secondlevel', 'thirdlevel'], 1)
add_element(root, ['toplevel', 'anotherlevel'], 2)
print root
输出
defaultdict(<function <lambda> at 0x7f1145eac7d0>,
{'toplevel': defaultdict(<function <lambda> at 0x7f1145eac7d0>,
{'secondlevel': defaultdict(<function <lambda> at 0x7f1145eac7d0>,
{'thirdlevel': 1}),
'anotherlevel': 2
})
})
如果要以递归方式实现此功能,则可以获取第一个元素并从当前root
获取子对象,并从path
中剥离第一个元素,以进行下一次迭代.
If you want to implement this in recursive manner, you can take the first element and get the child object from current root
and strip the first element from the path
, for the next iteration.
def add_element(root, path, data):
if len(path) == 1:
root[path[0]] = data
else:
add_element(root[path[0]], path[1:], data)
这篇关于如何在Python中动态构建树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!