向图中添加新节点是否会更改旧节点的索引?

2024-03-29 12:15:35 发布

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

我有一个networkx图形对象G。每个节点都有一个关于G.nodes()的索引。我跟踪节点索引,因为我使用邻接矩阵进行了一些计算,因为邻接矩阵中的每一行索引都对应于G.nodes()中的节点索引。但是现在我想向图中添加新节点,这会改变旧节点的索引吗?你知道吗

我不会移除任何节点。你知道吗

G = nx.Graph()

#add some nodes to G.

#record the indices of those nodes in a dictionary that maps from a node name to a node index from the list G.nodes()

#add more nodes and edges to G.

#Did the indices of the old nodes change?

Tags: oftheto对象fromnetworkxaddnode
1条回答
网友
1楼 · 发布于 2024-03-29 12:15:35

NetworkX将图形节点存储在类Graph的属性node中。因为node是一个字典,所以顺序不能保证并且可能会改变。你知道吗

如果你能提供更多关于你想要达到的目标的细节,我们可以帮你更多。您可以尝试保持从节点到名称的字典映射,或者如果只需要节点名称,也可以直接为节点分配名称:

G.add_node('John')
G.add_node('Jane')

也可以使用节点属性,例如

G.add_node(0, name='John', age=24)
G.add_node(1, name='Jane', age=27)

然后把它们读作

G.node[0]
>>> {'name': 'John', 'age': 24}

也可以将任意对象用作图形节点。你知道吗

相关问题 更多 >