<p>以下是第一原则的解决方案:</p>
<pre><code># We will build the tree of relationships, using a helper node class
class Node:
def __init__(self, value, parent=None, level=0):
self.value = value
self.parent = parent
self.level = level
self.children = []
def set_child(self, child):
child.level = self.level + 1
self.children.append(child)
# Helper function to insert nodes
def insert(node, new_node):
if new_node.parent == node.value:
# if the new node is a child, insert it
node.set_child(new_node)
else:
# otherwise, iterate over the children until you find its parent
if node.children:
for child in node.children:
insert(child, new_node)
# gather the level information for the tree
def node_print(node, values=[]):
if node.parent:
values.append((node.value, node.parent, node.level))
for child in node.children:
values = node_print(child, values=values)
return values
# Now get the data and build the tree
data = """b a
c a
d b
e c
f c
g f"""
rows = [y.split() for y in data.split("\n")]
for index, (child, parent) in enumerate(rows):
if index == 0:
node = Node(value=parent)
child_node = Node(value=child, parent=parent)
insert(node, child_node)
output = pd.DataFrame(data=node_print(node, values=[]), columns=['child', 'parent', 'level']).sort_values(by='level')
print(output)
child parent level
0 b a 1
2 c a 1
1 d b 2
3 e c 2
4 f c 2
5 g f 3
</code></pre>