Search code examples
pythonlistminimum

Python finding minimum values of functions of list items, but returning the list item


Sorry, it's a bit hard to explain my question in a title, but basically, I have a list of positions, and each position can be passed through a function to get a number that gives you data about the position. What I want to do is return the position with the lowest data value in the list, but I can't seem to find a way to do this.

A bit of pseudo code should help:

def posfunc(self,pos):
    x,y = pos
    return x**2-y

def minpos(self)
    returns position with the least x**2-y value

Solution

  • Python is pretty cool :D:

    min(positions, key=posfunc)
    

    From built-in documentation:

    >>> help(min)
    min(...)
        min(iterable[, key=func]) -> value
        min(a, b, c, ...[, key=func]) -> value
    
        With a single iterable argument, return its smallest item.
        With two or more arguments, return the smallest argument.
    

    And lambda's are worth mentioning here:

    min(positions, key=lambda x: x[0]**2 - x[1])
    

    Is roughly the same, but more readable I think, if you aren't using posfunc elsewhere.