Hi, friends. I wanna ask if there is a function which is able to take a list as argument and then return its top-k maximums?

John Nagle nagle at animats.com
Thu Apr 22 13:49:29 EDT 2010


Chris Rebert wrote:
> 2010/4/22 Jo Chan <csjcg2 at gmail.com>:
>> Hi,friends.
>>  I wanna ask if there is a function which is able to take a list as argument
>> and then return its top-k maximums?
>> I only know about max which is poorly a top-1 maximum function, now I want
>> more yet I am lazy enough that don't want to write one by myself.
> 
> http://docs.python.org/library/heapq.html#heapq.nlargest
> 
> Cheers,
> Chris
> --
> http://blog.rebertia.com

   Is "nlargest" smart enough to decide when it's cheaper to track the
N largest entries on a linear pass through the list than to sort?

   This is a typical optimization in SQL databases, by the way.  When
you write

	SELECT * FROM tab ORDER BY salary LIMIT 2;

you'll probably get a different algorithm than if you write

	SELECT * FROM tab ORDER BY salary LIMIT 200;

even if there's no key on "salary".

				John Nagle



More information about the Python-list mailing list