【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

相关推荐
happylifetree2 小时前
Python67:核心语法-函数进阶-参数类型(函数作为参数)
python
小羊没烦恼!3 小时前
铁道部新客票系统设计(二)
开发语言·前端·数据库·python·oracle·c#·php
quantdash_cc4 小时前
从实时行情到价格观察表:用 Python 和 Pandas 构建策略输入数据
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
镜子AI4 小时前
镜子AI工程实践:用 Python 做 GEO 实体一致性审计,并自动生成 JSON-LD 结构化数据
人工智能·python·json
罗湖老棍子5 小时前
【例 1】Sightseeing Trip(信息学奥赛一本通- P1494)(洛谷-P10927)
数据结构·算法·图论·最短路·floyd·最小环
stsdddd7 小时前
YOLO算法建筑工地安全帽目标检测数据集16881张:标注核对笔记
算法·yolo·目标检测
CV爱数码8 小时前
论文精读|Learned Primal-Dual:把原始–对偶算法展开成网络
图像处理·算法·计算机视觉·ct·重建·断层扫描
2601_962885728 小时前
如何用 Python 计算 VaR 和 CVaR(在险价值)?
开发语言·python
yuniko-n8 小时前
【算法】约瑟夫环问题
java·算法
李航19838 小时前
DeepSeekAI建模三 - 实战建模一组柜子
人工智能·python·计算机视觉·ai·ai编程