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?
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.
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.
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()
andnsmallest()
] perform best for smaller values of n. For larger values, it is more efficient to use thesorted()
function. Also, whenn==1
, it is more efficient to use the built-inmin()
andmax()
functions. If repeated usage of these functions is required, consider turning the iterable into an actual heap.
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