我以扁平的方式表示类别层次。
类别层次结构是
category1
category4
category6
category5
category7
category2
category3
我用字典把这个作为列表储存起来
^{pr2}$将这个类别列表转换为层次列表的最佳方法是什么
[{'name': 'category1',
'subcategory': [{'name': 'category4',
'subcategory': [{'name': 'category6', 'subcategory': []}]},
{'name': 'category5',
'subcategory': [{'name': 'category7', 'subcategory': []}]}]},
{'name': 'category2', 'subcategory': []},
{'name': 'category3', 'subcategory': []}]
你的问题和我在Calculating the Path from Parent Child Relationships 回答的问题非常相似
我注意到您的数据结构中似乎有很多多余的字段。基本上,您可以通过以下方式表示帖子中的信息:
为你重新编写代码。在
^{pr2}$输出:
为了把它变成一个嵌套字典,我建议您参考What is the best way to implement nested dictionaries?
我们从给定
index
和root
节点标识的make_tree
开始现在我们需要一种方法
^{pr2}$make_node
-这是我们将输入数据中的元素转换为输出树的元素的地方当然,现在我们需要一种基于输入数据的} ,这样我们就可以高效地查找所有子节点
make_index
的方法。我们使用itertools^{最后,我们编写
main
来将它们绑定在一起。注意数据不会为每次迭代重新编制索引或过滤全程序演示
程序输出
相关问题 更多 >
编程相关推荐