• 查找最大或最小的 N 个元素


    使用内置的heapd模块

    In [1]: import heapq
    
    In [2]: nums = [1,8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
    
    In [3]: print(heapq.nlargest(2,nums))
    [42, 37]
    
    In [4]: print(heapq.nlargest(5,nums))
    [42, 37, 23, 23, 18]
    
    In [5]: print(heapq.nsmallest(5,nums))
    [-4, 1, 2, 2, 7]

    两个函数都能接受一个关键字参数,用于更复杂的数据结构中

    In [6]: 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}
       ...: ]
    In [11]: print(heapq.nsmallest(3,portfolio,key=lambda s: s['price']))
    [{'price': 16.35, 'name': 'YHOO', 'shares': 45}, {'price': 21.09, 'name': 'FB', 'shares': 200}, {'price': 31.75, 'name': 'HPQ', 'shares': 35}]
    
    In [12]: print(heapq.nsmallest(2,portfolio,key=lambda s: s['price']))
    [{'price': 16.35, 'name': 'YHOO', 'shares': 45}, {'price': 21.09, 'name': 'FB', 'shares': 200}]

    那么如果你想在集合中找到最小和最大的值

    因为在底层实现里面,首先会先将集合数据进行堆排序后放入一个列表中

    In [1]: import heapq
    
    In [2]: nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2
       ...: ]
    
    In [3]: heap=list(nums)
    
    In [4]: heap
    Out[4]: [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
    
    In [5]: heapq.heapify(heap)
    
    In [6]: heap
    Out[6]: [-4, 2, 1, 23, 7, 2, 18, 23, 42, 37, 8]
    
    In [7]: heap[0]
    Out[7]: -4
    
    In [8]: heapq.heappop(heap)
    Out[8]: -4
    
    In [9]: heapq.heappop(heap)
    Out[9]: 1
    
    In [10]: heapq.heappop(heap)
    Out[10]: 2
    
    In [11]: heapq.heappop(heap)
    Out[11]: 2
    
    In [12]: heapq.heappop(heap)
    Out[12]: 7
    
    In [13]: heap
    Out[13]: [8, 23, 18, 23, 42, 37]

    堆数据结构最重要的特征是 heap[0] 永远是最小的元素。并且剩余的元素可以很容易的通过调用heapq.heappop() 方法得到, 该方法会先将第一个元素弹出来,然后用下一个最小的元素来取代被弹出元素(这种操作时间复杂度仅仅是 O(log N),N 是堆大小

    当要查找的元素个数相对比较小的时候,函数 nlargest() 和 nsmallest() 是很合适的。 如果你仅仅想查找唯一的最小或最大(N=1)的元素的话,那么使用 min() 和 max() 函数会更快些。 类似的,如果 N 的大小和集合大小接近的时候,通常先排序这个集合然后再使用切片操作会更快点 ( sorted(items)[:N] 或者是 sorted(items)[-N:] )。 需要在正确场合使用函数 nlargest() 和 nsmallest() 才能发挥它们的优势 (如果 N 快接近集合大小了,那么使用排序操作会更好些)。
  • 相关阅读:
    Java +安卓 定时任务
    android动画解析(初级)
    语义化版本 2.0.0
    团队中的 Git 实践
    Spring和SpringBoot比较,解惑区别
    Spring boot 拦截器和过滤器
    [ERROR] Failed to execute goal org.apache.maven.plugins:maven-install-plugin:2.4:install (default-cli) on project kircp-js-plan-resource: The packaging for this project did not assign a file to the bu
    Java函数优雅之道
    在springMVC的controller中获取request,response对象的一个方法
    Kotlin 数据类型(数值类型)
  • 原文地址:https://www.cnblogs.com/zcqdream/p/7211282.html
Copyright © 2020-2023  润新知