我有一个嵌套的数据结构,其中每个元素都可以是可迭代的或不可迭代的。我想构建一个图,以在网络中转换此嵌套数据结构(我想到了networkx
包)。每个元素都是带有Tuple
的{{1}},其中值可以是整数或Iterable。
我的最终图形应该看起来像这样,其中每个箭头就像所有缩进元素的边缘(即mainbox1连接到bigbox2,smallbox3,mediumbox4)
(ID, value)
我努力创建一种可以满足我要求的算法。我认为它应该是递归的(添加每个项目,直到没有更多的嵌套为止),但是我没有成功编写实现。
这是我的出发点。
mainbox1 -->
bigbox2 -->
mediumbox5
smallbox6
smallbox3
mediumbox4 -->
smallbox7
答案 0 :(得分:2)
示例数据中的元组存在一些问题。我做了一些更正,此代码有效
import networkx as nx
def rec_make(g, root, nodes):
for node in nodes:
g.add_edge(root, node[0])
if isinstance(node[1], list):
rec_make(g, node[0], node[1])
def main():
g = nx.Graph()
example = [('mainbox1', [('bigbox2', [
('mediumbox5', 5),
('smallbox6', 6)
]), ('smallbox3', 3), ('mediumbox4', [
('smallbox7', 7)
])])]
rec_make(g, example[0][0], example[0][1])
print("Nodes in G: ", g.nodes())
print("Edges in G: ", g.edges())
您正得到您想要的:
Nodes in G: ['mainbox1', 'bigbox2', 'mediumbox5', 'smallbox6', 'smallbox3', 'mediumbox4', 'smallbox7']
Edges in G: [('mainbox1', 'bigbox2'), ('mainbox1', 'smallbox3'), ('mainbox1', 'mediumbox4'), ('bigbox2', 'mediumbox5'), ('bigbox2', 'smallbox6'), ('mediumbox4', 'smallbox7')]