1.4 查找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]
>>>

python 2.7.6 和 python3.4.0 win7 64位 都有效


这两个函数还接受 key参数 用以处理更复杂的数据结构


>>> portfolio = [{'name': "IBM", 'shares': 100, 'price': 91.1},
         {'name': "AAPL", 'shares': 50, 'price': 543.2},
         {'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=lambda s: s['price'])
>>> expensive = heapq.nlargest(2, portfolio, key=lambda s: s['price'])
>>> cheap
[{'shares': 45, 'name': 'YHOO', 'price': 16.35}, {'shares': 200, 'name': 'FB', 'price': 21.09}, {'shares': 35, 'name': 'HPQ', 'price': 31.75}]
>>> expensive
[{'shares': 50, 'name': 'AAPL', 'price': 543.2}, {'shares': 75, 'name': 'ACME', 'price': 115.65}]
>>>


python 2.7.6 和 python 3.4.0 win7 64位 都有效


讨论:

   如果你只是寻找最大或最小的字,heap还有更好的方法,可以通过将数据转化成列表并想推一样排序。

>>> nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
>>> heap = list(nums)
>>> heapq.heapify(heap)
>>> heap
[-4, 2, 1, 23, 7, 2, 18, 23, 42, 37, 8]
>>>


heap[0]永远都是最小值。而且之后的元素可以通过heapq.heappop()方法轻易的找到,该方法会删除当前的最小值并以次小值来替换


>>> heapq.heappop(heap)
-4
>>> heap
[1, 2, 2, 23, 7, 8, 18, 23, 42, 37]
>>> heapq.heappop(heap)
1
>>> heap
[2, 2, 8, 23, 7, 37, 18, 23, 42]


这两个方法 在你试图相关的元素的最小值是特别合适。如果你只是先找出最大或最小(N =1时)时,它通常快于max() 和 min()。同样的,如果N与相关的数据集合一样大,它们也快于 先排序 后取片段的做法。还有一段不想翻了-。-  大意是要注意 相关模块的实现。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章