从整数列表中过滤最多20个值

编程入门 行业动态 更新时间:2024-10-19 22:20:55
本文介绍了从整数列表中过滤最多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.

重要说明 来自文档

后两个函数[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个值

本文发布于:2023-11-30 09:38:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649523.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最多   整数   列表中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!