【popexizhi:
heapq 的nlargest 和 nsmallest 这个好用啊,可以支持key,这个之前统计自己还重写过一个,嘻嘻,mark 。py2/py3都支持啊!
】
>>> import heapq >>> nums = [1,2,3,4,5,6,7,8,9] >>> heapq.nlargest(2, nums) [9, 8] >>> heapq.nsmallest(2, nums) [1, 2] >>> portfo = [{"name": "IBM", "p":"12.5"}, ] KeyboardInterrupt >>> portfo = [{"name": "IBM", "p":"12.5"},{"name": "I", "p":"12.51"},{"name": "IB", "p":"12.153"}] >>> heapq.nsmallest(2, portfo, key=lambda s: s['p']) [{'name': 'IB', 'p': '12.153'}, {'name': 'IBM', 'p': '12.5'}] >>> heapq.nlargest(2, portfo, key=lambda s: s['p']) [{'name': 'I', 'p': '12.51'}, {'name': 'IBM', 'p': '12.5'}]
没有评论:
发表评论