【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

相关推荐
BK贝壳1 小时前
bool-hybrid-array 的 GPU_opt 与 cjx:一个没显卡就报错的开关,一个把 800 字压到 96 字节的编码
python
BD_Marathon5 小时前
安装Jupyter notebook
ide·python·jupyter
Zlzxzw5 小时前
End-to-End Autonomous Generation of Human Assembly Plans
python
Wellijohn5 小时前
2000 个请求、30% 失败率:我把 Python 批量并发的限流和重试参数算了一遍
后端·python·性能优化
Logintern097 小时前
deep agents 多智能体模式——规划与委派
python·langchain
2601_967980119 小时前
Python 办公自动化合集 ⑰:Excel自动计算——总和/平均分/最大值
python·pycharm·办公自动化·数据处理·excel自动计算
民乐团扒谱机11 小时前
【超详细】基频音高提取算法之SWIPE 算法深度解析:频谱匹配的精度极限与工程边界
人工智能·算法
饮水桶_T11 小时前
C++ stack & queue复习笔记
开发语言·笔记·算法
星恒随风11 小时前
从0实现C++ AI大模型接入SDK(四):大模型API接入、公共数据结构设计与日志库封装
linux·服务器·数据结构·c++·人工智能