在这里我试图做一个布尔值,如果一对大小为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)
最佳答案
如果您查看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)
中评估类似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))
关于python - 查找networkx中每对节点之间的边缘,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59442107/