使用 Python 从二维网格图中的索引中恢复节点
Recovering nodes from indices in 2D grid graph using Python
此代码生成一个二维网格图,其索引对应于节点:{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
(交换 key/value)
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]
这是你想做的吗?
此代码生成一个二维网格图,其索引对应于节点:{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
(交换 key/value)
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]
这是你想做的吗?