按权重对网格图排序

Sort a grid graph by weights

我有一个网格图,它的边是元组的元组列表,代表节点:

G.edges = [((0, 0), (1, 0)), ..., ((15, 14), (15, 15))]

此外,每个元素都有一个权重:

G[(0,1)][(0,2)] = {'weight': 0.59}

如何按权重排序G.edges?我用 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()]    

这是一个例子:

from networkx import grid_graph
import numpy as np
field_shape = (2, 2)
G = grid_graph(dim=list(field_shape))
edge_weights = np.array([[e, np.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()]

for edge in G.edges():
    print(f"{edge[0]} -> {edge[1]} = {G[edge[0]][edge[1]]['weight']}")

print()
sorted_edges = sorted(G.edges(), key=lambda edge: G[edge[0]][edge[1]]['weight'])
for edge in sorted_edges:
    print(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