系列教程导航

  1. Python基础教程
  2. 在SublimeEditor中配置Python环境
  3. Python代码中添加注释
  4. Python中的变量的使用
  5. Python中的数据类型
  6. Python中的关键字
  7. Python字符串操作
  8. Python中的list操作
  9. Python中的Tuple操作
  10. Pythonmax()和min()–在列表或数组中查找最大值和最小值
  11. Python找到最大的N个(前N个)或最小的N个项目
  12. Python读写CSV文件
  13. Python中使用httplib2–HTTPGET和POST示例
  14. Python将tuple开箱为变量或参数
  15. Python开箱Tuple–太多值无法解压
  16. Pythonmultidict示例–将单个键映射到字典中的多个值
  17. PythonOrderedDict–有序字典
  18. Python字典交集–比较两个字典
  19. Python优先级队列示例

简介

本文介绍如何使用 Python 标准库 heapq 中的 nlargest()nsmallest() 函数,从元素集合中查找最大(或最小)的 N 个元素。

使用 heapq 模块查找最大或最小的 N 个项目

Python 的 heapq 模块提供了高效的堆队列算法,可用于从集合中查找 N 个最大或最小的项目。该模块主要包含以下两个核心函数:

  1. nlargest(): 查找最大的 N 个元素。
  2. nsmallest(): 查找最小的 N 个元素。

在简单可迭代对象中查找项目

对于简单的数字列表,可以直接使用这两个函数获取前 N 个最大值或最小值。

示例代码 (example1.py):

import heapq

nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]

# 查找最大的 3 个元素
print(heapq.nlargest(3, nums.html))
# 输出:[42, 37, 23]

# 查找最小的 3 个元素
print(heapq.nsmallest(3, nums.html))
# 输出:[-4, 1, 2]

在复杂可迭代对象中查找项目

当处理包含字典或其他复杂对象的列表时,可以通过 key 参数指定排序的依据字段。

示例代码 (example2.py):

import heapq

portfolio = [
    {'name': 'IBM', 'shares': 100, 'price': 91.1},
    {'name': 'AAPL', 'shares': 50, 'price': 543.22},
    {'name': 'FB', 'shares': 200, 'price': 21.09},
    {'name': 'HPQ', 'shares': 35, 'price': 31.75},
    {'name': 'YHOO', 'shares': 45, 'price': 16.35},
    {'name': 'ACME', 'shares': 75, 'price': 115.65}
]

# 查找价格最低的 3 个股票
cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'].html)
print(cheap.html)
# 输出:
# [
#   {'price': 16.35, 'name': 'YHOO', 'shares': 45},
#   {'price': 21.09, 'name': 'FB', 'shares': 200},
#   {'price': 31.75, 'name': 'HPQ', 'shares': 35}
# ]

# 查找价格最高的 3 个股票
expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'].html)
print(expensive.html)
# 输出:
# [
#   {'price': 543.22, 'name': 'AAPL', 'shares': 50},
#   {'price': 115.65, 'name': 'ACME', 'shares': 75},
#   {'price': 91.1, 'name': 'IBM', 'shares': 100}
# ]
性能提示:
如果您只是想查找单个最小或最大项(即 N=1),直接使用内置的 min()max() 函数速度会更快。

学习愉快!