美文网首页
python模块---heapq

python模块---heapq

作者: 堪怜咏絮才 | 来源:发表于2020-04-03 09:31 被阅读0次
    import heapq
    
    
    print(heapq.__all__)
    # ['heappush', 'heappop', 'heapify', 'heapreplace', 'merge', 'nlargest', 'nsmallest', 'heappushpop']
    '''
    heappush(heap, item):将 item 元素加入堆。
    heappop(heap):将堆中最小元素弹出。
    heapify(heap):将堆属性应用到列表上。
    heapreplace(heap, x):将堆中最小元素弹出,并将元素x 入堆。
    merge(*iterables, key=None, reverse=False):将多个有序的堆合并成一个大的有序堆,然后再输出。
    heappushpop(heap, item):将item 入堆,然后弹出并返回堆中最小的元素。
    nlargest(n, iterable, key=None):返回堆中最大的 n 个元素。
    nsmallest(n, iterable, key=None):返回堆中最小的 n 个元素。
    '''
    my_data = list(range(10))
    my_data.append(0.5)
    print(my_data)      # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0.5]
    heapq.heapify(my_data)      # 将堆属性作用于my_data上
    print(my_data)              # [0, 0.5, 2, 3, 1, 5, 6, 7, 8, 9, 4]
    heapq.heappush(my_data, 3.5)
    print(my_data)              # [0, 0.5, 2, 3, 1, 3.5, 6, 7, 8, 9, 4, 5]
    res = heapq.heappop(my_data)    # 弹出堆中最小的元素
    print(res)                  # 0
    heapq.heapreplace(my_data, 1.5) # 弹出最小的元素,并将1.5压入堆中
    print(my_data)              # [1, 1.5, 2, 3, 4, 3.5, 6, 7, 8, 9, 5]
    print(heapq.nlargest(3, [1,2,3,4,5,6]))         # [6, 5, 4]
    print(heapq.nsmallest(3, [1,2,3,4,5,6]))        # [1, 2, 3]
    

    相关文章

      网友评论

          本文标题:python模块---heapq

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