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

参考《python cookbook》

总结写在前面,

  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() 找到字典列表中三个价格最高的字典和三个价格最低的字典
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)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容