使用Python从二维网格图的索引中恢复节点



此代码生成一个2D网格图,其索引对应于节点:{1: (0, 0),2: (0, 1), 3: (0, 2), 4: (1, 0), 5:(1, 1), 6: (1, 2), 7: (2, 0), 8: (2, 1), 9: (2, 2)}。但是,我想确定与索引对应的特定节点。附加所需的输出。

import numpy as np
import networkx as nx
G = nx.grid_2d_graph(3,3)
nodes= {i:n for i, n in enumerate(G.nodes, start=1)}
edges = {i:e for i, e in enumerate(G.edges, start=1)}
A1 = nx.adjacency_matrix(G) 
A=A1.toarray()
G = nx.convert_node_labels_to_integers(G)
G = nx.relabel_nodes(G, {node:node+1 for node in G.nodes})
nx.draw(G, with_labels=True,pos=nx.spring_layout(G))
A1 = nx.adjacency_matrix(G) 
A=A1.toarray()
print([A]) 

Indices= [(1, 1),(2, 2)]

期望的输出是

Nodes=[5,9]

如果您以另一种方式构建nodes(交换键/值)

nodes = {n: i for i, n in enumerate(G.nodes, start=1)}

然后

indices= [(1, 1), (2, 2)]
result = [nodes[i] for i in indices]

给你

[5, 9]

那是你想做的吗?

最新更新