Python 数据结构图中的边排序

Python 数据结构图中的边排序,python,sorting,tuples,nodes,Python,Sorting,Tuples,Nodes,我有一个边相互连接的图。我将如何按照权重编号将图中节点的边从低到高进行排序 edges = { ("a", "b"): 1, ("a", "c"): 7, ("a", "d"): 3, ("b", "c"): 2, ("f", "b"): 6, (&q

我有一个边相互连接的图。我将如何按照权重编号将图中节点的边从低到高进行排序

edges = {
    ("a", "b"): 1,
    ("a", "c"): 7,
    ("a", "d"): 3,
    ("b", "c"): 2,
    ("f", "b"): 6,
    ("c", "d"): 1,
    ("c", "e"): 8,
    ("d", "e"): 4,
    ("e", "f"): 1,
    ("f", "g"): 3,
}

其中a-g是节点,数字是边的权重。用python编写。

您可以将
dict
键提取到
列表中,然后对
列表进行排序

edges = {('a', 'b'): 1, ('a', 'c'): 7, ('a', 'd'): 3, ('b', 'c'): 2, ('f', 'b'): 6, ('c', 'd'): 1, ('c', 'e'): 8, ('d', 'e'): 4, ('e', 'f'): 1, ('f', 'g'): 3}
edgeList = sorted(edges.keys(), key = edges.get)
edges.keys()
是一种
dict
方法,它将获得一个
dict\u keys
对象。基本上是围绕
dict
中使用的键列表的包装器对象。
sorted
函数的第二个参数是将用于对
sorted
的第一个参数中提供的iterable进行排序的条件