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與相關的數據集合一樣大,它們也快於 先排序 後取片段的做法。還有一段不想翻了-。-  大意是要注意 相關模塊的實現。

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