python中heapq的库是什么_Python标准库之heapq

功能介绍

该模块主要是用来实现堆排序。最大堆中的父节点大于或等于两个子节点,最小堆中的父节点小于或等于子节点

创建堆

在heapq中有两种方法,其一是用heapd.heappush()将值加入堆中,二是使用heapq.heapify(list)来实现

import heapq

'''

heapq.heappush(head,item)

- Push the value item onto the heap,maintaining the heap invariant.

heapq.heappop(heap)

- Pop and return the smallest item from the heap, maintaining the heap invariant.

if the heap is empty,IndexError is raised.To access the smallest item withouut popping it

'''

nums = [2,3,5,1,54,23,132]

heap = []

for num in nums:

heapq.heappush(heap,num)#加入值

print(heap[0])#获取最小值

print([heapq.heappop(heap) for _ in range(len(nums))])#打印排序结果

# out:[1,2,3,5,23,54,132]

# 第二种

nums = [2,3,5,1,54,23,132]

heapq.heapify(nums)

print([heap.heappop(heap) for _ in range(len(nums))])

# out:[1,2,3,5,23,54,132]

合并堆

heapq 中还有heapq.merge(*iterables)方法,用于合并多个 排序后的序列形成一个排序后的序列,返回排序后的值的迭代器

'''

函数定义:

heapq.merge(*iterables)

- Merge multiple sorted inputs into a single sorted output(for example, merge timestamped,entries from mutiple log files).Return an itreator over the sorted values.

- Similar to sorted

'''

import heapq

num1 = [32, 3, 5, 34, 54, 23, 132]

num2 = [23, 2, 12, 656, 324, 23, 54]

num1 = sorted(num1)

num2 = sorted(num2)

res = heapq.merge(num1,num2)

print(list(res))

访问堆

利用heapq.heappop()弹出最小值

import heapq

nums = [2, 43, 45, 23, 12]

heapq.heapify(nums)

print(heapq.heappop(nums))#out: 2

res = [heapq.heappop(nums) for _ in range(len(nums))]

print(res)

如果需要删除堆中最小元素并且加入一元素,可以使用heapq.heapreplace()函数

import heapq

nums = [1,2,4,5,3]

heapq.heapify(nums)

heapq.heapreplace(nums,23)

print([heapq.heappop(nums) for _ in range(len(nums))])

#out:[2,3,4,5,23]

获取最小堆或最大堆

如果需要获取堆中的最大或者最小的范围值,则可以使用heapq.nlargest()或heapq.nsmallest()函数

'''

heapq.nlargest(n, iterable[, key])

- Return a list with the n largest elements from the dataset defined by iterable.

- key if provided, specifies a function of one argument that is used to extract a comparison key from each element in the iterable: key=str.lower

- Equivalent to: sorted(iterable, key=key, reverse=True)[:n]

'''

import heapq

nums = [1,2,3,4,5]

print(heapq.nlargest(3,nums))

print(heapq.nsmallest(3,nums))

#out:[3,4,5]

#out:[1,2,3]

这两个函数还接收key参数,用于dict或其他数据结构使用

import heapq

from pprint import pprint

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)

"""

输出:

[{'name': 'YHOO', 'price': 16.35, 'shares': 45},

{'name': 'FB', 'price': 21.09, 'shares': 200},

{'name': 'HPQ', 'price': 31.75, 'shares': 35}]

[{'name': 'AAPL', 'price': 543.22, 'shares': 50},

{'name': 'ACME', 'price': 115.65, 'shares': 75},

{'name': 'IBM', 'price': 91.1, 'shares': 100}]

"""

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值