zoukankan      html  css  js  c++  java
  • Python中查找最大或最小的N个元素

    heapq 模块有两个函数:

    nlargest()和nsmallest()

    例如:

    >>> import heapq
    >>> nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
    >>> print(heapq.nlargest(3, nums)) # Prints [42, 37, 23]
    >>> print(heapq.nsmallest(3, nums)) # Prints [-4, 1, 2]
    >>> 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'])
    >>> expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])

    这些方法是基于堆数据结构实现的,对于查找的元素个数较少的时候比较合适

    如果仅仅想查找最大或者最小(N=1)的元素的话,用min()或者max()比较合适

    如果 N 的大小和集合大小接近的时候,通常先排序这个集合然后再使用切片操作会更快点

    >>> sorted(items)[:N]

     参考至《Python Cookbook》http://python3-cookbook.readthedocs.io/zh_CN/latest/

  • 相关阅读:
    verilog RTL编程实践之四
    TB平台搭建之二
    hdu3466 Proud Merchants
    poj2411 Mondriaan's Dream (用1*2的矩形铺)
    zoj3471 Most Powerful
    poj2923 Relocation
    hdu3001 Travelling
    poj3311 Hie with the Pie
    poj1185 炮兵阵地
    poj3254 Corn Fields
  • 原文地址:https://www.cnblogs.com/kwebi/p/9120483.html
Copyright © 2011-2022 走看看