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

    
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # Created by xuehz on 2017/2/24
    
    """
    怎样从一个集合中获得最大或者最小的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'])
    
    print(cheap)
    print(expensive)
    '''
    [{'shares': 45, 'price': 16.35, 'name': 'YHOO'}, {'shares': 200, 'price': 21.09, 'name': 'FB'}, {'shares': 35, 'price': 31.75, 'name': 'HPQ'}]
    [{'shares': 50, 'price': 543.22, 'name': 'AAPL'}, {'shares': 75, 'price': 115.65, 'name': 'ACME'}, {'shares': 100, 'price': 91.1, 'name': 'IBM'}]
    '''
    
    """
    当要查找的元素个数相对比较小的时候,函数 nlargest() 和 nsmallest() 是很合适的。
    如果你仅仅想查找唯一的最小或最大(N=1)的元素的话,那么使用 min() 和 max() 函数会更快些。 类似的,
    如果N的大小和集合大小接近的时候,通常先排序这个集合然后再使用切片操作会更快点 ( sorted(items)[:N] 或者是 sorted(items)[-N:] )。
    """
    
  • 相关阅读:
    HDU 2553 N皇后问题
    HDU 1251 统计难题(Trie tree)
    NYOJ 325 zb的生日
    dedecms文章页调用tag关键词_增加内链和关键字密度
    用DEDECMS做手机网站
    DedeCMS模板文件结构
    DEDECMS如何让栏目外部链接在新窗口中打开
    dedecms arclist中的自增变量 autoindex的说明
    dedecms 分页样式
    dedecms 修改默认html存放目录
  • 原文地址:https://www.cnblogs.com/xuehaozhe/p/6436326.html
Copyright © 2011-2022 走看看