在列表中找到min - python

Ale*_*ric 2 python class

我正在做一种Dijkstra作为家庭作业.
这就是班级的Vertex样子.

class Vertex:
    def __init__(self, id, name):
        self.id = id
        self.name = name
        self.minDistance = float('inf')
        self.previousVertex = None
Run Code Online (Sandbox Code Playgroud)

在其他课程中我有一个列表,unvisited vertexes我想找到一个最小距离,所以我可以递归地使用VertexminDistance.

例如 unvisited = [Vertex1, Vertex2,...]

尝试用for循环来做,但通过迭代并将其保存到变量不起作用,因为它只保存了最后一个值.如何在列表中找到类属性的最小值?

Jan*_*era 6

更多Pythonic单线程:

minDistance = min(otherVertex.distance for otherVertex in unvisited)

  • 作为对此的补充,您可以找到与"minVertex = min(unvisited,key = operator.attrgetter('distance'))具有最小距离的`Vertex`` (3认同)