我想创建一个列表 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 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.
更多推荐
从整数列表中过滤最多20个值
发布评论