将树列表转换为层次结构字典
我有一个带有属性的元素列表:parent、level、is_leaf_node、is_root_node、is_child_node。
我想将此列表转换为层次结构字典。 输出字典示例:
{
'Technology':
{
'Gadgets':{},
'Gaming':{},
'Programming':
{
'Python':{},
'PHP':{},
'Ruby':{},
'C++':{}
},
'Enterprise':{},
'Mac':{},
'Mobile':{},
'Seo':{},
'Ui':{},
'Virtual Worlds':{},
'Windows':{},
},
'News':{
'Blogging':{},
'Economics':{},
'Journalism':{},
'Politics':{},
'News':{}
},}
我不知道算法。 怎么做?
I have a list of elements with attrs: parent, level, is_leaf_node, is_root_node, is_child_node.
I want to convert this list to hierarchy dict.
Example of output dict:
{
'Technology':
{
'Gadgets':{},
'Gaming':{},
'Programming':
{
'Python':{},
'PHP':{},
'Ruby':{},
'C++':{}
},
'Enterprise':{},
'Mac':{},
'Mobile':{},
'Seo':{},
'Ui':{},
'Virtual Worlds':{},
'Windows':{},
},
'News':{
'Blogging':{},
'Economics':{},
'Journalism':{},
'Politics':{},
'News':{}
},}
I don't know algorithm. How to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是一个不太复杂的递归版本,如所描述的 chmod 700 。 当然完全未经测试:
Here's a less sophisticated, recursive version like chmod 700 described. Completely untested of course:
没有父母的一切都是你的最高水平,所以首先要做出这些决定。 然后第二次遍历你的数组,找到顶层父级的所有内容,等等......它可以写成循环或递归函数。 除了“父母”之外,您实际上不需要提供任何信息。
Everything without a parent is your top level, so make those dicts first. Then do a second pass through your array to find everything with a parent at that top level, etc... It could be written as a loop or a recursive function. You really don't need any of the provided info besides "parent".
听起来您基本上想做的是拓扑排序的变体。 最常见的算法是源删除算法。 伪代码看起来像这样:
这显然在几个地方被破坏了(至少作为实际的 Python 代码)。 不过,希望能让您了解该算法的工作原理。 请注意,如果您拥有的项目中存在循环(假设项目 a 以项目 b 作为父项,而项目 b 以项目 a 作为父项),则这将严重失败。 但无论如何,这可能无法以您想要的格式表示。
It sounds like what you're basically wanting to do is a variant of topological sorting. The most common algorithm for this is the source removal algorithm. The pseudocode would look something like this:
This obviously is broken in a couple of places (at least as actual Python code). However, hopefully that will give you an idea of how the algorithm will work. Note that this will fail horribly if there's a cycle in the items you have (say item a has item b as a parent while item b has item a as a parent). But then that would probably be impossible to represent in the format you're wanting to do anyway.
像这样简单的事情可能会起作用:
Something simple like this might work:
一个很好的递归方法来做到这一点:
a nice recursive way to do it: