Filter a maximum of 20 values โ€‹โ€‹from a list of integers

I would like to create a maxValues โ€‹โ€‹list containing the top 20 values โ€‹โ€‹from the list of integers lst.

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

Is there more compact code to perform this task or even a built-in function?

+5
source share
2 answers

There heapq.nlargest() :

 maxvalues = heapq.nlargest(20, lst) 

From the doc:

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

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

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

IMPORTANT NOTICE from the document :

The last two functions [ nlargest and nsmallest ] are best suited for smaller n values. 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() .

+12
source
 sorted(lst)[-20:] 

is the shortest that I can think of. It will probably be faster.

(edited: first try finding min instead of max)

+5
source

Source: https://habr.com/ru/post/917763/


All Articles