(Python基础教程之十一)Python找到最大的N个(前N个)或最小的N个项目
- Python 基础教程
- 在 SublimeEditor 中配置 Python 环境
- Python 代码中添加注释
- Python 中的变量的使用
- Python 中的数据类型
- Python 中的关键字
- Python 字符串操作
- Python 中的 list 操作
- Python 中的 Tuple 操作
- Pythonmax()和 min()–在列表或数组中查找最大值和最小值
- Python 找到最大的 N 个(前 N 个)或最小的 N 个项目
- Python 读写 CSV 文件
- Python 中使用 httplib2–HTTPGET 和 POST 示例
- Python 将 tuple 开箱为变量或参数
- Python 开箱 Tuple–太多值无法解压
- Pythonmultidict 示例–将单个键映射到字典中的多个值
- PythonOrderedDict–有序字典
- Python 字典交集–比较两个字典
- Python 优先级队列示例
- python 中如何格式化日期
- 30 分钟 Python 爬虫教程
- 爬虫下载网页视频 (video blob.html)
- nlargest()
- nsmallest()
1.1。在简单的可迭代对象中查找项目
example1.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。查找复杂的可迭代项
example2.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://blog.jsdiff.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
浙公网安备 33010602011771号