从整数列表中过滤最多20个值 [英] Filter max 20 values from a list of integers
问题描述
我想创建一个列表 maxValues ,其中包含整数 lst 列表中的前20个值.
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?
推荐答案
有 heapq.nlargest()
:
maxvalues = heapq.nlargest(20, lst)
来自文档:
heapq.nlargest(n, iterable, key=None)
从
iterable
定义的数据集中返回具有n个最大元素的列表.key
(如果提供)指定了一个参数的函数,该函数用于从可迭代的每个元素中提取比较键:key=str.lower
等效于:sorted(iterable, key=key, reverse=True)[:n]
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 the iterable:key=str.lower
Equivalent to:sorted(iterable, key=key, reverse=True)[:n]
或者以相同的方式使用 heapq.nsmallest()
你想要最小的.
Or at the same way use heapq.nsmallest()
if you want the smallest.
重要说明 来自文档:
后两个函数[
nlargest
和nsmallest
]对于较小的n
值表现最佳.对于较大的值,使用sorted()
函数会更高效.另外,当n==1
时,使用内置的>和 max()
函数.
The latter two functions [
nlargest
andnsmallest
] perform best for smaller values ofn
. 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.
这篇关于从整数列表中过滤最多20个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!