程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

python之cookbook-day04

发布于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黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

4 0
收藏该文
已收藏

评论内容:(最多支持255个字符)