如何从嵌套数据结构创建具有节点和边缘的网络?

时间:2019-08-19 05:41:39

标签: python recursion nested networkx graph-theory

我有一个嵌套的数据结构,其中每个元素都可以是可迭代的或不可迭代的。我想构建一个图,以在网络中转换此嵌套数据结构(我想到了networkx包)。每个元素都是带有Tuple的{​​{1}},其中值可以是整数或Iterable。

我的最终图形应该看起来像这样,其中每个箭头就像所有缩进元素的边缘(即mainbox1连接到bigbox2,smallbox3,mediumbox4)

(ID, value)

我努力创建一种可以满足我要求的算法。我认为它应该是递归的(添加每个项目,直到没有更多的嵌套为止),但是我没有成功编写实现。

这是我的出发点。

mainbox1 --> 
            bigbox2 -->
                        mediumbox5
                        smallbox6
            smallbox3
            mediumbox4 -->
                        smallbox7

1 个答案:

答案 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')]
相关问题