浏览量 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}]
>>>
上一篇 搜索 下一篇