python 中三種方法找最大最小值

參考《python cookbook》

總結(jié)寫在前面,

  1. 本文主要介紹headpq 模塊,headpq 模塊中nlargest()nsmallest() 可以用來返回最大或者最小的n個元素的列表
  2. 如果只是簡單地想找到最小或最大的元素(N=1時),那么用min()和 max()會更加快
  3. 如果N和集合本身的大小差不多大,通常更快的方法是先對集合排序,然后做切片操作(例如,使用sorted(items)[:N]或者sorted(items)[-N:])。
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2024/7/15 下午9:28
# @Author  : s
# 利用nlargest() 和 nsmallest() 找到列表中三個最大值和三個最小值
import heapq
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
print(heapq.nlargest(3, nums))
print(heapq.nsmallest(3, nums))
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2024/7/15 下午9:28
# @Author  : s
# 利用nlargest() 和 nsmallest() 找到字典列表中三個價(jià)格最高的字典和三個價(jià)格最低的字典
import heapq

dict_list = [{'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': 'YH0O', 'shares': 45, 'price': 16.35},
             {'name': 'ACME', 'shares': 75, 'price': 115.65}]
cheap = heapq.nsmallest(3, dict_list, key=lambda s: s['price'])
expensive = heapq.nlargest(3, dict_list, key=lambda s: s['price'])
print(cheap)
print(expensive)
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2024/7/15 下午9:28
# @Author  : sixixi
import heapq
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
h1 = list(nums)
heapq.heapify(h1) # heapify堆總是會把列表的最小值放在h1[0]
h2 = heapq.heappop(h1)
print(h1)
print(h2)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容