Python 按权重对网格图排序
我有一个网格图,它的边是元组的元组列表,表示节点:Python 按权重对网格图排序,python,sorting,lambda,grid,networkx,Python,Sorting,Lambda,Grid,Networkx,我有一个网格图,它的边是元组的元组列表,表示节点: G.edges = [((0, 0), (1, 0)), ..., ((15, 14), (15, 15))] 此外,每个元素都有一个权重: G[(0,1)][(0,2)] = {'weight': 0.59} 如何根据权重对G边进行排序?我用key=lambda尝试了很多东西,但到目前为止没有任何效果 对于可复制性,完整代码为: from networkx import grid_graph field_shape = (16, 16)
G.edges = [((0, 0), (1, 0)), ..., ((15, 14), (15, 15))]
此外,每个元素都有一个权重:
G[(0,1)][(0,2)] = {'weight': 0.59}
如何根据权重对G边进行排序?我用key=lambda
尝试了很多东西,但到目前为止没有任何效果
对于可复制性,完整代码为:
from networkx import grid_graph
field_shape = (16, 16)
G = grid_graph(dim=list(field_shape))
edge_weights = np.array([[e, random.rand()] for e in G.edges()]) # shape (nb_edges, 2)
for e, weight in edge_weights:
G[e[0]][e[1]]['weight'] = weight # Adds weights to all edges ((G[(0,1)][(0,2)]) = {'weight': 0.59})
nodes = [n for n in G.nodes()]
下面是一个例子:
从networkx导入网格图
将numpy作为np导入
字段_形状=(2,2)
G=网格图(尺寸=列表(字段形状))
边权重=np.array([[e,np.random.rand()]用于e in G.edges()])#形状(nb_边,2)
对于e,边中的权重\u权重:
G[e[0][e[1]['weight']=weight#向所有边添加权重((G[(0,1)][(0,2)])={'weight':0.59})
nodes=[n代表G.nodes()中的n]
对于G.边()中的边:
打印(f“{edge[0]}->{edge[1]}={G[edge[0]]][edge[1]][weight']}”)
打印()
已排序的_边=已排序的(G.edges(),key=lambda边:G[edge[0]][edge[1]['weight']))
对于排序的_边中的边:
打印(f“{edge[0]}->{edge[1]}={G[edge[0]]][edge[1]][weight']}”)
输出:
(0, 0) -> (1, 0) = 0.7516163148696177
(0, 0) -> (0, 1) = 0.25352872203948684
(0, 1) -> (1, 1) = 0.7781608787306042
(1, 0) -> (1, 1) = 0.08342751486451083
(1, 0) -> (1, 1) = 0.08342751486451083
(0, 0) -> (0, 1) = 0.25352872203948684
(0, 0) -> (1, 0) = 0.7516163148696177
(0, 1) -> (1, 1) = 0.7781608787306042
请用python提供一个带有权重的示例图。是的,我刚刚意识到,我添加了它:)太棒了!!它起作用了,实际上我尝试了一些非常相似的东西,但并不完全正确:)