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.)
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.
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 .
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().
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.
heapq.nlargest
:
>>> import heapq, random >>> heapq.nlargest(3, (random.gauss(0, 1) for _ in xrange(100))) [1.9730767232998481, 1.9326532289091407, 1.7762926716966254]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With