heapd如果学过数据结构就知道 堆排序,python提供了一个堆队列的模块heapq能很容易实现堆排序
如果要获取一个列表中N个最大最小的元素,heapd提供了两个函数:nlargest()
和nsmallest
import heapqnums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2] print(heapq.nlargest(3, nums)) # Prints [42, 37, 23]print(heapq.nsmallest(3, nums)) # Prints [-4, 1, 2]
两个函数都能接受一个关键字参数,用于更复杂的数据结构中:
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}] cheap = heapq.nsmallest(3, portfolio, key=s['price']) expensive = heapq.nlargest(3, portfolio, key=s['price'])