正如我在一篇评论中所指出的,如果你有任何控制权的话,你应该强烈考虑改变你的传入数据结构。元组的顺序列表绝对不是理想的。不过,如果你把它当作一棵树来对待,这是可能的。让我们构建一个(正常的)数据结构来解析它class Node(object):
def __init__(self, name, level, parent=None):
self.children = []
self.name = name
self.level = level
self.parent = parent
def make_child(self, othername, otherlevel):
other = self.__class__(othername, otherlevel, self)
self.children.append(other)
return other
现在您应该能够以某种合理的方式迭代数据结构
^{pr2}$
一旦你的结构完成,你就可以对它进行迭代。在这里,如果您选择深度优先还是广度优先,那么让我们做一个DFS来简化实现。在def parse_tree(any_node):
"""Given any node in a singly-rooted tree, returns a dictionary
of the form requested in the question
"""
def _parse_subtree(basenode):
"""Actually does the parsing, starting with the node given
as its root.
"""
if not basenode.children:
# base case, if there are no children then return an empty dict
return {}
subresult = {}
for child in basenode.children:
subresult.update({child.name: _parse_subtree(child)})
return subresult
cursor = any_node
while cursor.parent:
cursor = cursor.parent
# finds the root node
result = {}
for child in cursor.children:
result[child.name] = _parse_subtree(child)
return result
然后输入元组列表et voilatuple_list = [(1, 'line 1'), (2, 'line 2'), (3, 'line 3'), (1, 'line 4')]
last_node = make_nodes(tuple_list)
result = parse_tree(last_node)
# {'line 1': {'line 2': {'line 3': {}}}, 'line 4': {}}