Home > Mobile >  use min & max functions on objects list
use min & max functions on objects list

Time:11-21

so I have a list of objects that I made and every object has the var y. so I want to use the min function to find the lowest y of them without creating a new list of this var or use loops.

from random import randint

class Dot():
    def __init__(self, x=randint(-100, 100), y=randint(-100, 100)):
        self.x, self.y = x, y
d1, d2, d3, d4, d5 = Dot(), Dot(), Dot(), Dot(), Dot()

dots = [d1, d2, d3, d4, d5]

So now I'm trying yo find the lowest y of the dots with the min function without using a list of y for that, I want to use only the list I already created there. I already tried that:

min(dots.y)

but this try is really stupid and I knew it has very low chance to work, so it didn't work of course. I'm using python 3.10 by the way so tell me if I need newer version.

CodePudding user response:

Try to use key= parameter of min():

from random import randint


class Dot:
    def __init__(self, x=None, y=None):
        if x is None:
            x = randint(-100, 100)

        if y is None:
            y = randint(-100, 100)

        self.x, self.y = x, y



d1, d2, d3, d4, d5 = Dot(), Dot(), Dot(), Dot(), Dot()

dots = [d1, d2, d3, d4, d5]

print(min(dots, key=lambda d: d.y).y)

Prints (for example):

6

EDIT: The default argument is only get evaluated once, so I've put the random generation into function body. Credits to @Thierry

  • Related