Everfighting
9/7/2017 - 3:11 AM

找到最大或最小的N个元素

找到最大或最小的N个元素

import heapq  
dicts = [     
  {'name':'cbb','price':1221},     
  {'name':'bbc','price':212},     
  {'name':'cbc','price':12},     
  {'name':'bcb','price':112} 
  ] 
print(heapq.nlargest(2, dicts, key=lambda s:s['price'])) 
print(heapq.nsmallest(2, dicts, key=lambda s:s['price']))