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

Bengt Richter bokr at oz.net
Fri Dec 2 03:05:47 EST 2005


On 1 Dec 2005 05:45:54 -0800, "Niels L Ellegaard" <niels.ellegaard at gmail.com> wrote:

>I just started learning python and I have been wondering. Is there a
>short pythonic way to find the element, x, of a list, mylist, that
>maximizes an expression f(x).
>
>In other words I am looking for a short version of the following:
>
>pair=[mylist[0],f(mylist[0])]
>for x in mylist[1:]:
>     if f(x) > pair[1]:
>           pair=[x,f(x)]
>

Reversing the order of the pair:

 >>> mylist = range(10)
 >>> def f(x): return 10-(x-5)**2
 ...
 >>> [f(x) for x in mylist]
 [-15, -6, 1, 6, 9, 10, 9, 6, 1, -6]

Then one line should do it:

 >>> max((f(x),x) for x in mylist)
 (10, 5)

Ok, be picky ;-)

 >>> pair = list(reversed(max((f(x),x) for x in mylist)))
 >>> pair
 [5, 10]

Regards,
Bengt Richter



More information about the Python-list mailing list