如何使用 networkx 查找任意两个节点之间的边数?

How to find the number of edges bewteen any two nodes using networkx?

存在任何形式来计算分隔 2 个节点的边数,例如,如果我们有节点 "a"、"b"、"c" 和 "d"一种形式 "a"-"b"-"c"-"d" (其中“-”是一条边)我需要计算 "a" 和 [=21= 之间的边].

实例如下。我有一个很大的图表,但是在这个 link 你可以看到一张图片 https://drive.google.com/file/d/0B7GayK8MGGtCcVhRMncyM0VMc2c/view?usp=sharing

graph 在这种情况下有 2806 个节点,我需要知道例如有多少条边将 616 的节点 608 分开。我认为 number_of_edges 函数可以帮助我,但我认为现在只有 returns 是否连接了 2 个节点(因为 returns 像这样的代码中的 1 或 0)

    for k in id1: #id1 is a list of nodes
        for l in id2: #id2 is a list of nodes
            print graph.number_of_edges(k,l)

在不知道你尝试了什么并且没有示例图的情况下,我会给你一个简单的例子。它可能会为您解决问题。

我将使用 newtworkx 和 numpy 从 adjacency matrix 制作一个 4 节点、4 边图。

import matplotlib.pyplot as plt
import networkx as nx
import numpy as np

adjacency_matrix = np.array([[0,1,0,1], [1,0,1,0], [0,1,0,1], [1,0,1,0]])
print adjacency_matrix

这将打印我们的图表:

[[0 1 0 1]
 [1 0 1 0]
 [0 1 0 1]
 [1 0 1 0]]

现在将这个邻接矩阵输入到 networkx 中:

rows, cols = np.where(adjacency_matrix == 1)
edges = zip(rows.tolist(), cols.tolist())
gr = nx.Graph()
gr.add_edges_from(edges)

绘制它:

nx.draw_networkx(gr)
plt.show() 

现在我们可以通过以下方式查看哪些节点相互连接:

print gr.number_of_edges(0, 1) # clearly has an edge
print gr.number_of_edges(2, 0) # no edge between 2 and 0

正如预期的那样打印:

1
0

因此,如果您从 number_of_edges(a, b) 得到 0,则 a 和 b 不相邻(不是它们之间的边)。

[编辑:如果我们想找到 2 和 0 之间的所有路径,您可以执行以下操作

for path in nx.all_simple_paths(gr, source=2, target=0):
    print(path)
# prints
# [2, 1, 0]
# [2, 3, 0]

或者求最短路径:

p = nx.shortest_path(gr,source=2, target=0)
# [2, 1, 0]

在这种情况下你可以说:

num_edges = len(p) - 1 # num_edges = 2

]