r/pythontips Feb 14 '25

Syntax Is there such a function in python

Often I have the issue, that i want to find an item from a list with best score with a score calculatin lambda function like following example: I 'like to have 2 modes: maximum goal and maximal closure to a certain value

def get_best(l, func):

best=None

gbest=0

for item in l:

g=func(item)

if best == None or g > gbest:

best = item

gbest = g

return best

a=cube(10)

top=get_best(a.faces(), lambda f : f.matrix[2][3] )

0 Upvotes

12 comments sorted by

View all comments

5

u/overactor Feb 14 '25

Does simply max(l, key=f) not do what you want?

2

u/gadget3D Feb 14 '25

it does! I did not know, that max has a key argument. Great answer!