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

bonono at gmail.com bonono at gmail.com
Thu Dec 1 10:01:48 EST 2005


Duncan Booth wrote:
> wrote:
>
> >> 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)
>
> It might be better to do:
>
>    max((f(x),i,x) for i,x in enumerate(mylist))[2]
>
> as that will handle the case where x is not comparable but f(x) is.
>
> e.g.
> >>> mylist = (3j, 5j+2, 1j)
> >>> max((abs(x),i,x) for i,x in enumerate(mylist))[2]
> (2+5j)
thanks. I don't know what max can or cannot compare.




More information about the Python-list mailing list