(Python基础教程之十一)Python找到最大的N个(前N个)或最小的N个项目

  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 优先级队列示例
  20. python 中如何格式化日期
  21. 30 分钟 Python 爬虫教程
  22. 爬虫下载网页视频 (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()函数的]速度更快。

学习愉快!

posted on 2020-05-09 07:33  Java码界探秘  阅读(1318)  评论(0)    收藏  举报

导航