Alessandro Petric
Alessandro Petric

Reputation: 33

Find min in list - python

I'm doing a kind of Dijkstra as homework.
This is how the class Vertex looks.

class Vertex:
    def __init__(self, id, name):
        self.id = id
        self.name = name
        self.minDistance = float('inf')
        self.previousVertex = None

In other class I have a list of unvisited vertexes and I want to find a minimum distance, so I can recursively work with the Vertex having that minDistance.

e.g. unvisited = [Vertex1, Vertex2,...]

Tried to do it with for cycle, but by iterating it and saving it to a variable didn't work as it saved only the last value. How can I find a min value of a class atribute in list?

Upvotes: 2

Views: 250

Answers (1)

Jan Šimbera
Jan Šimbera

Reputation: 466

A more Pythonic one-liner:

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

Upvotes: 6

Related Questions