【问题标题】:Does adding new nodes to a graph change the indices of the old nodes?向图中添加新节点会改变旧节点的索引吗?
【发布时间】:2014-11-11 19:51:22
【问题描述】:

我有一个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?

【问题讨论】:

  • 您能否发布更多代码,以便我们更清楚地看到您的要求?

标签: python networkx


【解决方案1】:

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}

您也可以使用任意对象作为图形节点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-14
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多