遍历变量以连接每个节点 | Python图中的节点连通性

0 投票
5 回答
1519 浏览
提问于 2025-04-17 04:02

我想找出图中节点1和其他节点之间的连接情况。输入的文本文件格式如下:

1 2 1
1 35 1
8 37 1

接下来还有167行。第一列表示源节点,第二列表示目标节点,最后一列表示边的权重。

我正在尝试从输入文件中读取源节点和目标节点,并在它们之间形成一条边。接下来,我需要确定这个网络是否是连通的(也就是说,图中只有一个部分,没有子部分)。这里是我的代码:

from numpy import*
import networkx as nx
G=nx.empty_graph()

for row in file('out40.txt'):
    row = row.split()
    src = row[0]
    dest = row[1]
    #print src
    G.add_edge(src, dest)
    print src, dest

for i in range(2, 41):
    if nx.bidirectional_dijkstra(G, 1, i): print "path exists from 1 to ", i

我手动添加边的方式是:

G.add_edge(1, 2)

这样做虽然有效,但太繁琐了,不适合像我这样的较大输入文件。当我手动添加边时,if循环的条件可以正常工作,但对于上面的代码却出现了以下错误:

in neighbors_iter
raise NetworkXError("The node %s is not in the graph."%(n,))
networkx.exception.NetworkXError: The node 2 is not in the graph.

任何帮助都将非常感谢!

5 个回答

0

来自 Networkx文档

for row in file('out40.txt'):
    row = row.split()
    src = row[0]
    dest = row[1]
    G.add_nodes_from([src, dest])
    #print src
    G.add_edge(src, dest)
    print src, dest

错误信息说明图 G 中没有你想要连接的节点。

2

不确定这对你来说是否可行,但你知道 networkx内置支持多种图形文本格式 吗?

边列表格式 看起来非常适合你的情况。具体来说,下面这个方法可以直接读取你的输入文件,不需要你写额外的代码:

G = nx.read_weighted_edgelist(filename)

如果你想去掉权重(因为你不需要它们),你可以接着这样做:

for e in G.edges_iter(data=True):
    e[2].clear()                   #[2] is the 3rd element of the tuple, which 
                                   #contains the dictionary with edge attributes
2

在你的代码中,你添加了节点 "1""2" 等等(因为从文件读取的数据会是字符串,除非你特别把它们转换成其他类型)。

但是,你接下来却试图引用节点 12。我猜 networkx 可能认为 2 == "2" 这两个是不相等的。

试着把这个...

G.add_edge(src, dest)

改成这个:

G.add_edge(int(src), int(dest))

撰写回答