首页 > 解决方案 > 查找networkx中每对节点之间的边

问题描述

在这里,我试图做一个布尔值,如果一对大小为 3 的节点之间不存在边,则打印这对

所以,我想使用 G.adj 并且到目前为止我知道如何将它与大小为 2 的对一起使用,但在这里我没有得到正确的结果。

例子:

(2, 5, 9) -> 打印

(0, 7, 8) - > 不打印

%pylab inline
import warnings
warnings.filterwarnings("ignore")
import networkx as nx

n = 10
G = nx.Graph()
G.add_nodes_from(range(n))
G.add_edge(0, n-1)
G.add_edge(0, 5)
G.add_edge(1, 6)
G.add_edge(2, 7)
G.add_edge(3, 8)
G.add_edge(4, 9)         
for i in range(n-1):
    G.add_edge(i, i+1)

s = set(itertools.combinations(G.nodes, 3))
for i in s:
    if i not in G.adj:
        print(i)


标签: pythongraphnetworkxcombinatorics

解决方案


如果你看G.adj

AdjacencyView({0: {9: {}, 5: {}, 1: {}}, 1: {6: {}, 0: {}, 2: {}}, 2: {7: {}, 1: {}, 3: {}}, 3: {8: {}, 2: {}, 4: {}}, 4: {9: {}, 3: {}, 5: {}}, 5: {0: {}, 4: {}, 6: {}}, 6: {1: {}, 5: {}, 7: {}}, 7: {2: {}, 6: {}, 8: {}}, 8: {3: {}, 7: {}, 9: {}}, 9: {0: {}, 4: {}, 8: {}}})

这基本上是一个嵌套字典。(6,5,0)因此,评估in 之类的东西G.adj会返回False,导致你的三元组被打印出来。您可以编写更详细的逻辑来查询G.adj,例如:

adj = G.adj
for x,y,z in s:
    if (adj[x].get(y), adj[x].get(z), adj[y].get(z)) == (None, None, None):
        print((x,y,z))

或者,您可以通过邻接矩阵:

am = nx.adjacency_matrix(G).todense()
s = set(itertools.combinations(G.nodes, 3))
for x,y,z in s:
    if (am[x,y], am[x,z], am[y,z]) == (0,0,0):
        print((x,y,z))

推荐阅读