1

As the code below, I know how to get the item that maximize a function from a list, but I also want to get the maximized value together with the item. In reality I have a very computationally expensive function so I don't want to run the function again. Here I just use a sigmoid function as an example.

import math

lst = list(range(100))
maxnum = max(lst, key=lambda x: 1 / (1 + math.exp(-x)))
maxval = 1 / (1 + math.exp(-maxnum))
print(maxnum, maxval)
Shaun Han
  • 2,676
  • 2
  • 9
  • 29

1 Answers1

1

Use a tuple to store both maxnum and maxval, as follows, then pass as key the value in the second position (using itemgetter in the code below):

import math
from operator import itemgetter

lst = list(range(100))


def sigmoid(x):
    return 1 / (1 + math.exp(-x))

result = max((e, sigmoid(e))  for e in lst, key=itemgetter(1))


print(result)

Output

(37, 1.0)
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76