
Python中的heapq模块提供了一种堆队列heapq类型,这样实现堆排序等算法便相当方便,这里我们就来详解Python中heapq模块的用法,需要的朋友可以参考下
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# -*- coding: utf-8 -*- __author__ = 'songhao' import heapq l = range(100) # 获取最大的是个元素 print(heapq.nlargest(10, l)) # 获取最小的是个元素 print(heapq.nsmallest(10, l)) |
# heapq 排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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['shares'])) # 根据价格进行排序; print(heapq.nlargest(3, portfolio, key=lambda s: s['price'])) |
输出结果是:
1 2 3 4 5 |
# /usr/local/bin/python3 "/Users/songhao/Desktop/Python3 入门和进阶/Python file/d7/c1.py" # [99, 98, 97, 96, 95, 94, 93, 92, 91, 90] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # [{'name': 'HPQ', 'shares': 35, 'price': 31.75}, {'name': 'YHOO', 'shares': 45, 'price': 16.35}, {'name': 'AAPL', 'shares': 50, 'price': 543.22}] # [{'name': 'AAPL', 'shares': 50, 'price': 543.22}, {'name': 'ACME', 'shares': 7 |
当要查找的元素个数相对比较小的时候,函数 nlargest() 和 nsmallest() 是很合适的。 如果你仅仅想查找唯一的最小或最大(N=1)的元素的话,那么使用 min() 和 max() 函数会更快些。 类似的,如果 N 的大小和集合大小接近的时候,通常先排序这个集合然后再使用切片操作会更快点 ( sorted(items)[:N] 或者是 sorted(items)[-N:] )。 需要在正确场合使用函数 nlargest() 和 nsmallest() 才能发挥它们的优势 (如果 N 快接近集合大小了,那么使用排序操作会更好些)。
