【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

相关推荐
开开心心就好13 分钟前
图片格式转换工具,右键菜单一键转换简化
linux·运维·服务器·python·django·pdf·1024程序员节
骥龙13 分钟前
1.2下、工欲善其事:物联网安全研究环境搭建指南
python·物联网·安全
AlenTech14 分钟前
200. 岛屿数量 - 力扣(LeetCode)
算法·leetcode·职场和发展
C雨后彩虹24 分钟前
竖直四子棋
java·数据结构·算法·华为·面试
Lxinccode35 分钟前
BUG(20) : response.text耗时很久, linux耗时十几秒, Windows耗时零点几秒
python·bug·requests·response.text·response.text慢
智航GIS38 分钟前
11.2 Matplotlib 数据可视化教程
python·信息可视化·matplotlib
技术净胜43 分钟前
Python 操作 Cookie 完全指南,爬虫与 Web 开发实战
前端·爬虫·python
海棠AI实验室1 小时前
第六章 日志体系:logging 让排错效率翻倍
python·logging
laufing1 小时前
flask_restx 创建restful api
python·flask·restful
不如自挂东南吱1 小时前
空间相关性 和 怎么捕捉空间相关性
人工智能·深度学习·算法·机器学习·时序数据库