发布于2019-08-07 16:26 阅读(545) 评论(0) 点赞(4) 收藏(3)
第一章:数据结构和算法
1.4 查找最大或最小的N个元素
问题:
怎样从一个集合中获得最大或者最小的 N 个元素列表?
解决方案:
heapq 模块有两个函数:nlargest() 和 nsmallest() 可以完美解决这个问题。
>>> import heapq >>> nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2] >>> print(heapq.nlargest(3, nums)) [42, 37, 23] >>> print(heapq.nsmallest(3, nums)) [-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}, {'na... ... ... ... ... ... me': 'ACME', 'shares': 75, 'price': 115.65} ]... >>> cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price']) >>> expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price']) >>> print(cheap) [{'name': 'YHOO', 'shares': 45, 'price': 16.35}, {'name': 'FB', 'shares': 200, 'price': 21.09}, {'name': 'HPQ', 'shares': 35, 'price': 31.75}] >>> print(expensive) [{'name': 'AAPL', 'shares': 50, 'price': 543.22}, {'name': 'ACME', 'shares': 75, 'price': 115.65}, {'name': 'IBM', 'shares': 100, 'price': 91.1}] >>>
讨论:
讨论 如果你想在一个集合中查找最小或最大的 N 个元素,并且 N 小于集合元素数量, 那么这些函数提供了很好的性能。因为在底层实现里面,首先会先将集合数据进行堆排 序后放入一个列表中:
>>> nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2] >>> import heapq >>> heap = list(nums) >>> heapq.heapify(heap) >>> heap [-4, 2, 1, 23, 7, 2, 18, 23, 42, 37, 8] >>> heapq.heappop(heap) -4 >>> heapq.heappop(heap) 1 >>> heapq.heappop(heap) 2 >>> heapq.heappop(heap) 2 >>> heapq.heappop(heap) 7 >>>
当要查找的元素个数相对比较小的时候,函数 nlargest() 和 nsmallest() 是很 合适的。如果你仅仅想查找唯一的最小或最大(N=1)的元素的话,那么使用 min() 和 max() 函数会更快些。类似的,如果 N 的大小和集合大小接近的时候,通常先排序这个 集合然后再使用切片操作会更快点(sorted(items)[:N] 或者是 sorted(items)[-N:] )。需要在正确场合使用函数 nlargest() 和 nsmallest() 才能发挥它们的优势(如果 N 快接近集合大小了,那么使用排序操作会更好些)。
作者:你敢说我不帅
链接:https://www.pythonheidong.com/blog/article/11521/ee0b823ac9c7e849d9e6/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!