python heapq

葫芦的运维日志

下一篇 搜索 上一篇

浏览量 3879

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}]
>>>



 

葫芦的运维日志

打赏

上一篇 搜索 下一篇
© 冰糖葫芦甜(bthlt.com) 2021 王梓打赏联系方式 陕ICP备17005322号-1