🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# Python 找到 N 个最大的或最小的项目 > 原文: [https://howtodoinjava.com/python/find-largest-smallest-items/](https://howtodoinjava.com/python/find-largest-smallest-items/) Python 示例使用`heapq`库中的`nlargest()`和 `nsmallest()`函数从元素集合中找到最大(或最小)的 N 个元素。 ## 1.使用`heapq`模块的`nlargest()`和 nsmallest() Python `heapq`模块可用于**从集合中找到 N 个最大或最小的项目**。 它具有两个辅助函数: 1. `nlargest()` 2. `nsmallest()` #### 1.1 在简单的可迭代对象中查找项目 ```py >>> import heapq >>> nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2] print(heapq.nlargest(3, nums)) >>> [42, 37, 23] print(heapq.nsmallest(3, nums)) >>> [-4, 1, 2] ``` #### 1.2 查找复杂的可迭代项 ```py >>> 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} ] >>> cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price']) >> cheap >>> [ {'price': 16.35, 'name': 'YHOO', 'shares': 45}, {'price': 21.09, 'name': 'FB', 'shares': 200}, {'price': 31.75, 'name': 'HPQ', 'shares': 35} ] >>> expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price']) >>> 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()`函数](https://howtodoinjava.com/python/max-min/)更快。 学习愉快!