Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast way to get N Min or Max elements from a list in Python

Tags:

python

sorting

I currently have a long list which is being sorted using a lambda function f. I then choose a random element from the first five elements. Something like:

f = lambda x: some_function_of(x, local_variable)
my_list.sort(key=f)
foo = choice(my_list[:4])

This is a bottleneck in my program, according to the profiler. How can I speed things up? Is there a fast, inbuilt way to retrieve the elements I want (in theory shouldn't need to sort the whole list). Thanks.

like image 733
Sort Me Out Please Avatar asked Feb 18 '10 13:02

Sort Me Out Please


People also ask

How do you find the max and min of a list in Python?

Use Python's min() and max() to find smallest and largest values in your data. Call min() and max() with a single iterable or with any number of regular arguments. Use min() and max() with strings and dictionaries.

What is the most efficient way to find the lowest and the highest value in a list?

The Python max() function is used to find the largest value in a list of values. The Python min() function is used to find the lowest value in a list. The list of values can contain either strings or numbers.


1 Answers

Use heapq.nlargest or heapq.nsmallest.

For example:

import heapq

elements = heapq.nsmallest(4, my_list, key=f)
foo = choice(elements)

This will take O(N+KlogN) time (where K is the number of elements returned, and N is the list size), which is faster than O(NlogN) for normal sort when K is small relative to N.

like image 196
interjay Avatar answered Sep 20 '22 07:09

interjay