heapq( Heap queue algorithm)库

heapq( Heap queue algorithm)库

从集合中取前n个最大,或最小的值

nlargest(n,iterable)前n个最大的,nsmallest(n,iterable)前n个最小的

import heapq

nums=[1,23,32,45,67,21,78,12]

print("3 largest",heapq.nlargest(3,nums))
print("3 smallest",heapq.nsmallest(3,nums))
3 largest [78, 67, 45]
3 smallest [1, 12, 21]

从字典中取前n个最大,或最小的值

nlargest(n,dicts,key)按照key取前n个最大的,nsmallest(n,dicts,key)按照key取前n个最小的

dicts=[
    {'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}
]

print("2 largest",heapq.nlargest(2,dicts,key=lambda s:s['price']))
print("2 smallest",heapq.nsmallest(2,dicts,key=lambda s:s['price']))
2 largest [{'name': 'AAPL', 'price': 543.22, 'shares': 50}, {'name': 'ACME', 'price': 115.65, 'shares': 75}]
2 smallest [{'name': 'YHOO', 'price': 16.35, 'shares': 45}, {'name': 'FB', 'price': 21.09, 'shares': 200}]

heapify(X),将list X转换为堆

print("heap before:",nums)
heapq.heapify(nums)
print("heap after:",nums)
heap before: [1, 23, 32, 45, 67, 21, 78, 12]
heap after: [1, 12, 21, 23, 67, 32, 78, 45]

heappush(heap, item)

往堆里push一个元素

heapq.heappush(nums,10)

print("push 10 :",nums)
push 10 : [1, 10, 21, 12, 67, 32, 78, 45, 23]

heappop(heap)

从堆中pop一个最小的值,并从堆中移除这个值, 如果heap为空,抛出异常:IndexError: index out of range

smallest = heapq.heappop(nums)
print(smallest)
print("pop after:",nums)
#smallest = heapq.heappop([])
1
pop after: [10, 12, 21, 23, 67, 32, 78, 45]

heappushpop(heap, item)

push一个元素 , 然后pop一个最小的元素,类似与先调用一个 heappush() 然后再调用一个heappop方法

smallest = heapq.heappushpop(nums,100)
print("heappushpop 100, ",smallest)

###push一个最小的值,
smallest = heapq.heappushpop(nums,1)
print("heappushpop smallest value 1 and then return :",smallest)
heappushpop 100,  10
heappushpop smallest value 1 and then return : 1

heapreplace(heap, item)

先pop最小的值,然后再push item,如果heap为空,抛出异常:IndexError: index out of range

smallest = heapq.heapreplace(nums,1)
print("heapreplace smallest value 1 and then return :",smallest)
heapreplace smallest value 1 and then return : 12

merge(*iterables, key=None, reverse=False)

合并多个集合,返回堆排序后的数据,类型为 iterator


newheap = heapq.merge(nums,[10,11,23])
print(newheap)

for item in newheap:
    print(item)
<generator object merge at 0x0000000004EB4AF0>
1
10
11
23
21
23
45
67
32
78
100
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值