Ciszko
Ciszko

Reputation: 195

Python - find minimum value greater than 0 in a list of instances

I have a list of instances (of Process class) named process_list. I'm strugling to find min value of attribute l_time greater than 0. This is how my class looks:

class Process:

    def __init__(self, id, a_time, p_time):
        self.id = id
        self.a_time = a_time
        self.p_time = p_time
        self.l_time = p_time
        self.w_time = 0
        self.ta_time = 0
        self.is_available = False

I tried something like:

current_process = min(i for i in process_list if i.l_time > 0)

it gives an error :

TypeError: '<' not supported between instances of 'Process' and 'Process'

Do I have to write a __gt__function somehow or is there a way to do it using lambda?

Upvotes: 1

Views: 1325

Answers (1)

Dani Mesejo
Dani Mesejo

Reputation: 61910

Use the key parameter of min:

class Process:

    def __init__(self, id, a_time, p_time):
        self.id = id
        self.a_time = a_time
        self.p_time = p_time
        self.l_time = p_time
        self.w_time = 0
        self.ta_time = 0
        self.is_available = False

process_list = [Process(1, 10, 10), Process(1, 5, 5), Process(1, -5, -5)]
result = min((p for p in process_list if p.l_time > 0), key= lambda x: x.l_time)

print(result.l_time)

Output

5

Upvotes: 7

Related Questions