从整数列表中过滤最多20个值 [英] Filter max 20 values from a list of integers

查看:92
本文介绍了从整数列表中过滤最多20个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个列表 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.

重要说明 来自文档:

后两个函数[nlargestnsmallest]对于较小的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个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆