python heapq

葫芦的运维日志

浏览量 5493 2018/09/11 18:03

>>> import heapq
>>> nums = [ -1,-300,2,-99,22,232,-9999,0]
>>> heapq.nlargest(3,nums)
[232, 22, 2]
>>> heapq.nsmallest(3,nums)
[-9999, -300, -99]
>>> portfolio=[{'name':'IBM','shares':100,'price':32.1}
... ,{'name':'TEN','shares':231,'price':20}
... ,{'name':'FUN','shares':12,'price':58}]
>>> cheap = heapq.nsmallest(3,portfolio,key=lambda s:s['price'])
>>> cheap
[{'price': 20, 'name': 'TEN', 'shares': 231}, 
{'price': 32.1, 'name': 'IBM', 'shares': 100}, 
{'price': 58, 'name': 'FUN', 'shares': 12}]
>>> expensive=heapq.nlargest(3,portfolio,key=lambda s:s['price'])
>>> expensive
[{'price': 58, 'name': 'FUN', 'shares': 12}, 
{'price': 32.1, 'name': 'IBM', 'shares': 100}, 
{'price': 20, 'name': 'TEN', 'shares': 231}]
>>>



 

📝 版权声明

本文作者:王梓 | 原文链接:https://www.bthlt.com/note/8-heapq

出处:葫芦的运维日志 | 转载请注明出处并保留原文链接

打赏

留言板

留言提交后需管理员审核通过才会显示

© 冰糖葫芦甜(bthlt.com) 2025 王梓打赏联系方式陕ICP备17005322号-1