如何解决使用循环根据权重对边进行排序
我有以下 2 个课程:
class Edge:
a: int
b: int
weight: int
def __init__(self,a: int,b: int,weight: int):
self.a = a
self.b = b
self.weight = weight
和
class Graph:
nodes: Dict[int,Node]
def __init__(self,n):
self.nodes = {i: Node(i) for i in range(n)}
# Returns a list with all edges in the graph
def all_edges(self) -> List[Edge]:
return [Edge(node.id,neighbour,weight) for _,node in self.nodes.items()
for neighbour,weight in node.neighbours.items() if node.id < neighbour]
我想获取所有边的列表,但要根据它们的权重按升序排列。 一种可能的方法是:
# Sort all edges by weight,ascending.
# Note that you Could do this with a loop as well.
edges = sorted(g.all_edges(),key=attrgetter("weight"))
我想知道如何使用循环来做到这一点?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。