Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to efficiently get the k bigger elements of a list in python

What´s the most efficient, elegant and pythonic way of solving this problem?

Given a list (or set or whatever) of n elements, we want to get the k biggest ones. ( You can assume k<n/2 without loss of generality, I guess) For example, if the list were:

l = [9,1,6,4,2,8,3,7,5] 

n = 9, and let's say k = 3. What's the most efficient algorithm for retrieving the 3 biggest ones? In this case we should get [9,8,7], in no particular order.

Thanks! Manuel

like image 610
Manuel Araoz Avatar asked Feb 11 '10 09:02

Manuel Araoz


People also ask

How do you find the nth largest number in an array in Python?

Suppose we have an unsorted array, we have to find the kth largest element from that array. So if the array is [3,2,1,5,6,4] and k = 2, then the result will be 5. We will sort the element, if the k is 1, then return last element, otherwise return array[n – k], where n is the size of the array.

How do you find the three largest numbers in a list in Python?

The max() Function — Find the Largest Element of a List. In Python, there is a built-in function max() you can use to find the largest number in a list.


1 Answers

Use nlargest from heapq module

from heapq import nlargest lst = [9,1,6,4,2,8,3,7,5] nlargest(3, lst) # Gives [9,8,7] 

You can also give a key to nlargest in case you wanna change your criteria:

from heapq import nlargest tags = [ ("python", 30), ("ruby", 25), ("c++", 50), ("lisp", 20) ] nlargest(2, tags, key=lambda e:e[1]) # Gives [ ("c++", 50), ("python", 30) ] 
like image 91
sharjeel Avatar answered Oct 01 '22 18:10

sharjeel