使用lambda支持heapq获取复杂对象集合的最大N项和最小N项
# -*- coding: utf-8 -*-mport heapqnums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]print heapq.nlargest(3, nums)print heapq.nsmallest(3, nums)portfolio = [ {'name': 'IBM', 'shares': 100, 'price': 91.1}, {'name': 'AAPL', 'shares': 50, 'price': 543.22}, {'name': 'FB', 'shares': 200, 'price': 21.09}, {'name': 'HPQ', 'shares': 35, 'price': 31.75}, {'name': 'YHOO', 'shares': 45, 'price': 16.35}, {'name': 'ACME', 'shares': 75, 'price': 115.65},]print heapq.nsmallest(3, portfolio, key=lambda s:s['price'])expensive = heapq.nlargest(3, portfolio, key=lambda s:s['price'])
out
[{'price': 16.35, 'name': 'YHOO', 'shares': 45}, {'price': 21.09, 'name': 'FB', 'shares': 200}, {'price': 31.75, 'name': 'HPQ', 'shares': 35}][{'price': 543.22, 'name': 'AAPL', 'shares': 50}, {'price': 115.65, 'name': 'ACME', 'shares': 75}, {'price': 91.1, 'name': 'IBM', 'shares': 100}]