【Python】【数据结构和算法】查找最大或最小的N个元素

除了直接排序,还可以利用heaq模块的nlargest()nsmallest()方法,例如:

python 复制代码
>>> nums = [3, 5, 2, 4, 1]
>>> smallest = heapq.nsmallest(3, nums)
>>> print(smallest)
[1, 2, 3]
>>> largest = heapq.nlargest(3, nums)
>>> print(largest)
[5, 4, 3]

参考

Python Cookbook 1.4

相关推荐
Omics Pro几秒前
Arc研究所Cell|全新虚拟细胞官方基准评测框架
大数据·人工智能·深度学习·算法·机器学习
白狐_7983 分钟前
408 数据结构|红黑树插入:只记两大类
数据结构
spencer_tseng30 分钟前
[j2cache ehcache.xml]/tmp/.ehcache-diskstore.lock (Permission denied)
xml·linux·python·ehcache·[j2cache
梦想不只是梦与想1 小时前
Python Web 框架:FastAPI
python·fastapi·web框架
玩大数据的龙威1 小时前
农经权二轮延包—全面取代人工公示图生成
python·arcgis
IT_Octopus2 小时前
JSON 日志里的 `{“$ref“:“$.xxx“}`:从 fastjson 兼容包到原生 fastjson2 的迁移实录
开发语言·python·json
geovindu2 小时前
python:HandWriting Recognition using paddlepaddle
开发语言·后端·python·paddlepaddle
CoderYanger2 小时前
A.每日一题:1140. 石子游戏 II
java·程序人生·算法·leetcode·游戏·职场和发展·深度优先
小雨笙笙2 小时前
机器学习:评估模型与选择
人工智能·算法·机器学习
高亦真2 小时前
今天是学习嵌入式的第35天
linux·学习·算法