Greg Kritzman
Greg Kritzman

Reputation: 93

Putting a pointer as a value in a method call [python]

I'm trying to have a function where I can put in a list and a pointer, and have it apply that pointer to the objects in the list to give me the object with the lowest value of that pointer.

def GetLowest(ListObject,Value):

    ObjectX=ListObject[0]

    for i in ListObject:

        if i.Value<=ObjectX.Value:

            ObjectX=i

    return ObjectX

Then I could do things like (assuming I have lists of these objects) GetLowest(Rectangles,Area) and have it check the area of each rectangle. Or maybe something more complex like GetLowest(Backpacks,Wearer.ShoeSize).

I'm going to want to use this in a few places around my program. Thanks in advance, guys!

Upvotes: 0

Views: 67

Answers (1)

mgilson
mgilson

Reputation: 310049

It looks to me like you would like to use the builtin min function. min takes an iterable (e.g. a list) and returns the minumum element. You can also give it a key function which is called to do the comparison.

e.g.:

smallest_rectangle = min(list_of_rectangles,key=lambda rect:rect.area)
backpack_with_small_shoes = min(backpacks,key=lambda b: b.wearer.shoe_size)

The various functions in the operator module are really useful here too. For example, the first statement above could be written as:

from operator import attrgetter
smallest_rectangle = min(list_of_rectangles,key=attrgetter('area'))

Upvotes: 4

Related Questions