A more pythonic way to find an item in a list that maximizes function

OK, I have this simple function that finds a list item that maximizes the value of another positive function.

def get_max(f, s):
    # f is a function and s is an iterable

    best = None
    best_value = -1

    for element in s:
        this_value = f(element)
        if this_value > best_value:
            best = element
            best_value = this_value
    return best

But I find it a very long time for a simple job. Actually it reminds me of Java (brrrr). Can someone show me a more pythonic and clean way to do this?

Thank!
Manuel

+3
source share
1 answer
def get_max(f, s):
  return max(s, key=f)
+14
source

Source: https://habr.com/ru/post/1732304/


All Articles