【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

相关推荐
沧海一笑-dj5 分钟前
【Python】Python学习笔记-初识 Python
python·python安装·python解释器
打工仔折腾 AI8 分钟前
FastAPI 从本机到生产服务器:Nginx+Gunicorn+Uvicorn 完整部署实录
人工智能·后端·python·nginx·fastapi·gunicorn
hetao173383711 分钟前
2026-09-17 hetao1733837 的刷题记录
c++·算法
hanchenxing22 分钟前
AI 数据管道重构:从函数堆到链式管道的可读性实践
python
hhzz28 分钟前
【OpenCV 入门到精通 10】视频分析与光流跟踪:背景减除与运动检测
人工智能·python·opencv·性能优化
蓝胖的四次元口袋29 分钟前
Python基础语法入门
python
Patrick在香港1 小时前
Python 抓 0.91 GB 香港法例:Agent 的进度该写进磁盘,不是写进上下文
爬虫·python·api·claude·香港
午彦琳1 小时前
2026.9.17
数据结构·算法·leetcode
ClinicTech1 小时前
实验室洗瓶机的清洗系统架构与自动化控制解析
java·python
洋洋不叫杨杨1 小时前
Codex 实战:用 AI 写运维脚本
大数据·python