Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter max 20 values from a list of integers

Tags:

python

list

max

I'd like to create a list maxValues containing top 20 values from a list of integers lst.

maxValues = []
for i in range(20):
  maxValues.append(max(lst))
  lst.remove(max(lst))

Is there a more compact code for achieving this task or even built-in function?

like image 212
xralf Avatar asked Mar 18 '12 09:03

xralf


People also ask

How do you filter a list in a list Python?

Short answer: To filter a list of lists for a condition on the inner lists, use the list comprehension statement [x for x in list if condition(x)] and replace condition(x) with your filtering condition that returns True to include inner list x , and False otherwise.

Can you call Max on a list Python?

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.


1 Answers

There's heapq.nlargest():

maxvalues = heapq.nlargest(20, lst)

From the doc:

heapq.nlargest(n, iterable, key=None)

Return a list with the n largest elements from the dataset defined by iterable. key, if provided, specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, key=str.lower). Equivalent to: sorted(iterable, key=key, reverse=True)[:n].

Or at the same way use heapq.nsmallest() if you want the smallest.

IMPORTANT NOTE from the doc:

The latter two functions [nlargest() and nsmallest()] perform best for smaller values of n. For larger values, it is more efficient to use the sorted() function. Also, when n==1, it is more efficient to use the built-in min() and max() functions. If repeated usage of these functions is required, consider turning the iterable into an actual heap.

like image 133
Rik Poggi Avatar answered Oct 23 '22 09:10

Rik Poggi