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

bonono at gmail.com bonono at gmail.com
Thu Dec 1 09:40:28 EST 2005


Niels L Ellegaard 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)]

this is already very short, what else you want? May be this :

max(((f(x), x) for x in mylist))

That is first generate the (f(x),x) pairs then find the max one(first
compare f(x) then x)




More information about the Python-list mailing list