从 python 列表中获取使函数最大化的项目以及最大值

Get the item that maximizes a function together with the maximized value from a python list

如下面的代码,我知道如何从列表中获取使函数最大化的项,但我还想与项一起获取最大值。实际上,我有一个计算量很大的函数,所以我不想再次 运行 该函数。这里我只是以一个sigmoid函数为例

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)

使用元组存储maxnummaxval,如下所示,然后将第二个位置的值作为键传递(在下面的代码中使用itemgetter):

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)

输出

(37, 1.0)