python heapq

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

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券