[[x,f(x)] for x in list that maximizes f(x)] <--newbie help
Duncan Booth
duncan.booth at invalid.invalid
Thu Dec 1 09:51:23 EST 2005
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)
More information about the Python-list
mailing list