美文网首页
找到最大或最小的N个元素

找到最大或最小的N个元素

作者: Little茂茂 | 来源:发表于2020-12-23 00:09 被阅读0次
    import heapq
    
    
    nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
    print(heapq.nlargest(3, nums))
    print(heapq.nsmallest(3, nums))
    
    portfolio = [
        {'name': 'IBM', 'share': 100, 'price': 91.1},
        {'name': 'APPL', 'share': 50, 'price': 543.22},
        {'name': 'FB', 'share': 200, 'price': 21.09},
        {'name': 'HPQ', 'share': 35, 'price': 31.75},
        {'name': 'YHOO', 'share': 45, 'price': 16.35},
        {'name': 'ACME', 'share': 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)
    
    # 寻找最大或最小的元素数量远小于元素总数
    heap = list(nums)
    heapq.heapify(heap)
    print(heapq)
    for _ in range(4):
        print(heapq.heappop(heap))
    
    # 寻找最大或最小元素
    print(max(nums))
    print(min(nums))
    
    # 寻找最大或最小元素数量和元素总数差不多
    print(sorted(nums)[:4])
    print(sorted(nums)[-4:])
    
    
    

    相关文章

      网友评论

          本文标题:找到最大或最小的N个元素

          本文链接:https://www.haomeiwen.com/subject/bunenktx.html