如何从嵌套数据结构创建具有节点和边的网络?
how to create a network with node and edges from nested data structure?
我有一个嵌套数据结构,其中每个元素都可以是可迭代的,也可以不是。我想构建一个图形来转换网络中的嵌套数据结构(为此我想到了 networkx
包)。每个元素都是 Tuple
和 (ID, value)
,其中值可以是整数或 Iterable。
我的最终图表应该看起来像这样,其中每个箭头就像所有缩进元素的边(即 mainbox1 连接到 bigbox2、smallbox3、mediumbox4)
mainbox1 -->
bigbox2 -->
mediumbox5
smallbox6
smallbox3
mediumbox4 -->
smallbox7
我努力创建一个可以满足我要求的算法。我以为应该是递归的(每一项都加到没有嵌套为止)但是我没有写实现成功
这是我的起点。
import networkx as nx
example = [('mainbox1',[('bigbox2', [('mediumbox5'),
('smallbox6')]),
('smallbox3'),
('mediumbox4', ('smallbox7'))
] )]
您的示例数据中的元组存在一些问题。我做了一些更正,此代码有效
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')]
我有一个嵌套数据结构,其中每个元素都可以是可迭代的,也可以不是。我想构建一个图形来转换网络中的嵌套数据结构(为此我想到了 networkx
包)。每个元素都是 Tuple
和 (ID, value)
,其中值可以是整数或 Iterable。
我的最终图表应该看起来像这样,其中每个箭头就像所有缩进元素的边(即 mainbox1 连接到 bigbox2、smallbox3、mediumbox4)
mainbox1 -->
bigbox2 -->
mediumbox5
smallbox6
smallbox3
mediumbox4 -->
smallbox7
我努力创建一个可以满足我要求的算法。我以为应该是递归的(每一项都加到没有嵌套为止)但是我没有写实现成功
这是我的起点。
import networkx as nx
example = [('mainbox1',[('bigbox2', [('mediumbox5'),
('smallbox6')]),
('smallbox3'),
('mediumbox4', ('smallbox7'))
] )]
您的示例数据中的元组存在一些问题。我做了一些更正,此代码有效
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')]