(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優先級隊列示例

Python示例使用heapq庫中的**nlargest()和nsmallest()**函數從元素集合中找到最大(或最小)的N個元素。

1.使用heapq模塊的nlargest()和nsmallest()

Python heapq模塊可用於從集合中查找N個最大或最小的項目。它有兩個功能可幫助–

  1. nlargest()
  2. 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()函數的]速度更快。

學習愉快!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM