Networkx:两个图之间的互连节点

时间:2017-12-20 08:17:44

标签: python networkx

我有图A.对于图A中的每个节点,我使用一些规则来转换节点的名称并决定将其添加到图B中。

所以现在我从B派生了B.我想知道是否有可能在A中的原始节点和B中的转换节点之间创建某种链接。

我无法找到使用networkx库执行此操作的方法。任何指针都会有所帮助......

1 个答案:

答案 0 :(得分:1)

节点可以具有属性。在图A中的每个节点中,您可以创建一个属性来保存图B中的相应节点。

在下面的代码中,图A有3个节点:1,2和3.图B是用节点1,4和9创建的(A中节点值的平方)。当B中的每个节点都被创建时,它的值存储在发起它的A节点的b_node属性中。

import networkx as nx

def main():
    # Create graph A
    a = nx.Graph()
    a.add_node(1)
    a.add_node(2)
    a.add_node(3)

    # Create graph B with nodes that are squares of the nodes in A
    # Add to each node in A an attribute (b_node) 
    # to hold the corresponding node in B
    b = nx.Graph()
    for node in a:
        a.add_node(node, b_node=node * node)
        b.add_node(node * node)

    print("A:")
    print(a.nodes.data())
    print("\nB:")
    print(b.nodes.data())

if __name__ == '__main__':
    main()

输出:

A:
[(1, {'b_node': 1}), (2, {'b_node': 4}), (3, {'b_node': 9})]

B:
[(1, {}), (4, {}), (9, {})]
相关问题