[[x,f(x)] for x in list that maximizes f(x)] <--newbie help

Duncan Booth duncan.booth at invalid.invalid
Fri Dec 2 04:05:31 EST 2005


bonono at gmail.com wrote:
> Thanks. In that case, would it be easier to understand(beside the
> original iterative loop) if I use reduce and lambda ?
> 
You could try putting them side by side and seeing which is easiest for 
someone to understand:

reduce(lambda (mv,mx), (v,x): mv > v and (mv,mx) or (v,x), ((f(x), x) for x 
in mylist)))
 
max((f(x),i,x) for i,x in enumerate(mylist))[2]

max_x, max_f = mylist[0], f(mylist[0])
for x in mylist[1:]:
    new_f = f(x)
    if new_f > max_f:
           max_x, max_f = x, new_f

IMO, the last is clearest (but needs a list rather than an iterator), the 
middle is most concise and not too hard to understand and the first is a 
complete mess. YMMV.



More information about the Python-list mailing list