zoukankan      html  css  js  c++  java
  • heapq模块

    当要查找的元素个数相对比较小的时候,函数 nlargest() 和 nsmallest() 是很合适的。 如果你仅仅想查找唯一的最小或最大(N=1)的元素的话,那么使用 min() 和 max() 函数会更快些。 类似的,如果 N 的大小和集合大小接近的时候,通常先排序这个集合然后再使用切片操作会更快点 ( sorted(items)[:N] 或者是 sorted(items)[-N:] )。 需要在正确场合使用函数 nlargest() 和 nsmallest() 才能发挥它们的优势 (如果 N 快接近集合大小了,那么使用排序操作会更好些)

    方法 

    取n个最大值和最小值

    • nlargest  相当于 sorted(iterable, key=key, reverse=True)[:n]
    • nsmallest 相当于 sorted(iterable, key=key)[:n]
    import heapq
    nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
    print(heapq.nsmallest(2, nums))
    print(heapq.nlargest(2, nums))
    [-4, 1]
    [42, 37]
    # 复杂的数据结构 可以通过key参数指定比较标准
    import
    heapq 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} ] print(heapq.nlargest(2, portfolio, key=lambda x: x['price'])) print(heapq.nsmallest(2, portfolio, key=lambda x: x['price'])) [{'name': 'AAPL', 'shares': 50, 'price': 543.22}, {'name': 'ACME', 'shares': 75, 'price': 115.65}] [{'name': 'YHOO', 'shares': 45, 'price': 16.35}, {'name': 'FB', 'shares': 200, 'price': 21.09}]
  • 相关阅读:
    约瑟夫环问题拓展 C/C++
    C/C++之STL简介
    详解约瑟夫环问题 C/C++
    HC-SR04超声波传感器
    TCRT5000 红外传感器
    win10的docker无法运行mysql的image,Public Key Retrieval is not allowed
    如何将docker默认的安装位置从C盘改为D盘?
    免费PDF阅读器
    A1B2B3
    动态代理
  • 原文地址:https://www.cnblogs.com/wc89/p/12658598.html
Copyright © 2011-2022 走看看