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

2024-09-28 17:27:43 发布

您现在位置:Python中文网/ 问答频道 /正文

存在任何形式来计算分隔2个节点的边数,例如,如果我们有节点“a”、“b”、“c”和“d”,形式为“a”-“b”-“c”-“d”(其中“-”是边),我需要计算“a”和“d”之间的边。在

真正的例子如下。我有一个很大的图,但是在这个链接中你可以看到一个图片https://drive.google.com/file/d/0B7GayK8MGGtCcVhRMncyM0VMc2c/view?usp=sharing

在本例中,图有2806个节点,我需要知道例如,有多少条边将616的节点608分开。我原以为number_of_edges函数可以帮助我,但现在我认为只有2个节点连接或不连接时才会返回(因为在这样的代码中返回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)

Tags: ofinnumberfor节点is链接形式
1条回答
网友
1楼 · 发布于 2024-09-28 17:27:43

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

我将使用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

这将打印我们的图表:

^{2}$

现在将这个邻接矩阵输入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() 

enter image description here

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

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)得到{},那么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

]

相关问题 更多 >