我有一个无向的NetworkX图,想找到所有的node_a邻居,它们也是node_b的邻居

时间:2019-03-03 14:15:02

标签: python networkx

直截了当的问题:如何找到node_a和node_b之间的所有邻居,并且最好的方法是什么?

我的代码是:

my_node_list_a = [ ... ]
my_node_list_b = [ ... ]

for c in my_node_list_a:
    for x in nx.neighbors(G, c):
        for y in my_node_list_b:
            for h in nx.neighbors(G, y):
                 if x in y:
                    print(x)

这是错误的代码。首先,我必须通过执行my_node_list_a手动填充my_node_list_bfor i in G.nodes(): print(i),并且只将要运行循环的节点放入数组中。

编辑

标题说邻居,但是我不是networkx的新手,所以它可能不是正确的术语。如果邻居仅表示距离为1的节点,那么是的,这就是我想要的。

但是,我还对连接数组my_node_list_amy_node_list_b中距离大于1的节点的节点感兴趣,所以如果有人可以告诉我如何做,也会很有用(基本上是为了告诉我它们之间的路径)

进一步编辑

我需要根据所选节点的邻居从主图G创建一个图。

最好的方法是什么?

2 个答案:

答案 0 :(得分:3)

要查找两个节点之间的公共邻居,可以使用函数common_neighbors()

import networkx as nx

G = nx.turan_graph(6, 2)

%matplotlib inline # jupyter notebook
nx.draw(G, with_labels=True)

list(nx.common_neighbors(G, 3, 5))
# [0, 1, 2]

graph

要查找两组节点(顶点)之间的公共邻居,可以使用函数node_boundary()

import networkx as nx
from itertools import chain

G = nx.grid_graph(dim=[5, 5])

list_A = [(3, i) for i in range(5)]
list_B = [(1, i) for i in range(5)]
intersec = nx.node_boundary(G, list_A) & nx.node_boundary(G, list_B)
# {(2, 1), (2, 0), (2, 3), (2, 2), (2, 4)}

color = []
for i in G.nodes():
    if i in intersec:
        col = 'green'
    elif i in chain(list_A, list_B):
        col = 'red'
    else:
        col = 'pink'
    color.append(col)

%matplotlib inline
nx.draw(G, with_labels=True, node_color=color, node_size=1000)

enter image description here

答案 1 :(得分:0)

您可以这样做: (如果您有一个大图,我会更改答案,以避免麻烦)

import networkx as nx

def keep_neighbors(graph, node):
    tokeep = set()
    for k, v in g[node].items():
        # print v.get('weight') == 1
        if v.get('weight') == 1:
            tokeep.add(k)
    return tokeep

if __name__ == '__main__':
    g = nx.Graph()
    g.add_edge('a', 'b', weight = 1)
    g.add_edge('a', 'c', weight = 1)
    g.add_edge('a', 'd', weight = 2)
    g.add_edge('a', 'e', weight = 1)
    g.add_edge('a', 'f', weight = 1)

    g.add_edge('z', 'c', weight = 1)
    g.add_edge('z', 'd', weight = 1)
    g.add_edge('z', 'e', weight = 1)

    g.add_edge('k', 'c', weight = 1)
    g.add_edge('k', 'd', weight = 1)
    g.add_edge('k', 'e', weight = 1)


    a = keep_neighbors(g, 'a')
    b = keep_neighbors(g, 'z')
    print(a) # set(['c', 'b', 'e', 'f'])
    print(b) # set(['c', 'e', 'd'])

    result = a & b
    print(result) # set(['c', 'e'])

    a = keep_neighbors(g, 'k')
    b = keep_neighbors(g, 'z')
    result = a & b
    print(result) # set(['c', 'e', 'd'])