本文實例講述了python找到最大或最小的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]>>>
這兩個函數接受一個參數key,允許其工作在更復雜的數據結構之上:
# example.py## Example of using heapq to find the N smallest or largest itemsimport heapqportfolio = [ {'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}]cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])print(cheap)print(expensive)Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:24:06) [MSC v.1600 32 bit (Intel)] on win32Type "copyright", "credits" or "license()" for more information.>>> ================================ RESTART ================================>>>[{'name': 'YHOO', 'price': 16.35, 'shares': 45}, {'name': 'FB', 'price': 21.09, 'shares': 200}, {'name': 'HPQ', 'price': 31.75, 'shares': 35}][{'name': 'AAPL', 'price': 543.22, 'shares': 50}, {'name': 'ACME', 'price': 115.65, 'shares': 75}, {'name': 'IBM', 'price': 91.1, 'shares': 100}]>>>如果正在尋找的最大或最小的N個元素,且相比于集合中元素的數量,N很小時,下面的函數性能更好。
這些函數首先會在底層將數據轉化為列表,且元素會以堆的順序排列。
>>> import heapq>>> nums=[1,8,2,23,7,-4,18,23,42,37,2]>>> heap=list(nums)>>> heap[1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]>>> heapq.heapify(heap) #heapify()參數必須是list,此函數將list變成堆,實時操作。從而能夠在任何情況下使用堆的函數。>>> heap[-4, 2, 1, 23, 7, 2, 18, 23, 42, 37, 8]>>> heapq.heappop(heap)#如下是為了找到第3小的元素-4>>> heapq.heappop(heap)1>>> heapq.heappop(heap)2>>>
堆(heap)最重要的特性就是heap[0]總是最小的元素。可通過heapq.heappop()輕松找到最小值,這個操作的復雜度為O(logN),N代表堆得大小。
總結:
1、當要找的元素數量相對較小時,函數nlargest()和nsmallest()才最適用。
2、若只是想找到最小和最大值(N=1)時,使用min()和max()會更快。
|
新聞熱點
疑難解答