系列教程导航

  1. Python 基础教程
  2. 在 SublimeEditor 中配置 Python 环境
  3. Python 代码中添加注释
  4. Python 中的变量的使用
  5. Python 中的数据类型
  6. Python 中的关键字
  7. Python 字符串操作
  8. Python 中的 list 操作
  9. Python 中的 Tuple 操作
  10. Python max()和 min()–在列表或数组中查找最大值和最小值
  11. Python 找到最大的 N 个(前 N 个)或最小的 N 个项目
  12. Python 读写 CSV 文件
  13. Python 中使用 httplib2–HTTP GET 和 POST 示例
  14. Python 将 tuple 开箱为变量或参数
  15. Python 开箱 Tuple–太多值无法解压
  16. Python multidict 示例–将单个键映射到字典中的多个值
  17. Python OrderedDict–有序字典
  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))
# 输出:[42, 37, 23]

# 查找最小的 3 个元素
print(heapq.nsmallest(3, nums))
# 输出:[-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'])
print(cheap)
# 输出:
# [
#   {'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'])
print(expensive)
# 输出:
# [
#   {'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() 函数速度会更快。

学习愉快!