Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: take max N elements from some list

Tags:

python

max

Is there some function which would return me the N highest elements from some list?

I.e. if max(l) returns the single highest element, sth. like max(l, count=10) would return me a list of the 10 highest numbers (or less if l is smaller).

Or what would be an efficient easy way to get these? (Except the obvious canonical implementation; also, no such things which involve sorting the whole list first because that would be inefficient compared to the canonical solution.)

like image 526
Albert Avatar asked Nov 18 '10 13:11

Albert


People also ask

How do you return a maximum value from 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. To use it, call the max() on a list of numbers. It then returns the greatest number in that list.

How do you find the top 3 values in Python?

If you want to get the indices of the three largest values, you can just slice the list. It also supports sorting from smallest to largest by using the parameter rev=False .

Can we use MAX function in list in Python?

The Python max() function returns the largest value in an iterable, such as a list. If a list contains strings, the last item alphabetically is returned by max().

How do you find the maximum multiple values in Python?

We can use the max() method in various ways to find the maximum or largest of a given iterable or for two or more arguments. Let us see how the method works with an iterable object, two or more values, with specified key function and for multiple iterable objects passed as arguments.


1 Answers

heapq.nlargest:

>>> import heapq, random >>> heapq.nlargest(3, (random.gauss(0, 1) for _ in xrange(100))) [1.9730767232998481, 1.9326532289091407, 1.7762926716966254] 
like image 84
Gareth Rees Avatar answered Sep 18 '22 07:09

Gareth Rees