1.4 找到最大或者最小的N個元素

一、N=1 使用min、max

如果只是簡單的想找到最小或最大的元素(N=1時),使用min和max最快

二、N約等於集合長度,先排序

如果N和集合的本身大小差不多,通常更快的方法是先對集合進行排序,然後做切片操作,例如sorted(items)[:N]或者sorted(items)[-N:]

三、N小於集合長度 使用heapq

如果我們想在某個集合中找到最大或者最小的N個元素,使用heapq中的nlargest和nsmallest,這兩個函數的實際實現會該劇使用它們的方式不同而有所不同,可能會相應的做出一些優化措施,比如當N接近集合大小的時候,採用先排序的方法

import heapq

nums = [1, 2, 3, 423, 54, 3232, -4, -554, 99932, 555]
print(heapq.nlargest(2, nums))
print(heapq.nsmallest(2, nums))

# 這兩個函數都可以使用key參數來處理複雜的數據結構

protfolio = [
    {'name': 'IBM', 'shares': 100, 'price': 92.1},
    {'name': 'I3B4M', 'shares': 100, 'price': 924.1},
    {'name': 'IB432M', 'shares': 100, 'price': 912.1},
    {'name': 'IB332M', 'shares': 100, 'price': 90.1},
    {'name': 'IB424M', 'shares': 100, 'price': 82.1},
    {'name': 'IB32M', 'shares': 100, 'price': 95.1},
]
cheap = heapq.nsmallest(3, protfolio, key=lambda x: x.get('price'))
expensive = heapq.nlargest(3, protfolio, key=lambda x: x.get('price'))
print(cheap)
print(expensive)

輸出
[99932, 3232]
[-554, -4]
[{‘name’: ‘IB424M’, ‘shares’: 100, ‘price’: 82.1}, {‘name’: ‘IB332M’, ‘shares’: 100, ‘price’: 90.1}, {‘name’: ‘IBM’, ‘shares’: 100, ‘price’: 92.1}]
[{‘name’: ‘I3B4M’, ‘shares’: 100, ‘price’: 924.1}, {‘name’: ‘IB432M’, ‘shares’: 100, ‘price’: 912.1}, {‘name’: ‘IB32M’, ‘shares’: 100, ‘price’: 95.1}]

四、更好的性能

如果N很小,那麼使用堆排序可能會性能更好

import heapq

nums = [1, 2, 3, 423, 54, 3232, -4, -554, 99932, 555]
heapq.heapify(nums)
print(nums)

輸出
[-554, 1, -4, 2, 54, 3232, 3, 423, 99932, 555]
堆最重要的特性就是heap[0]總是最小的那個元素,此外,接下來的元素可依次通過heapq.heappop()方法輕鬆找到,該方法會將第一個最小元素彈出,然後以第二小的元素取代之,時間複雜度是O(logN),N代表堆的大小,例如要找到第三小的元素可以用

import heapq

nums = [1, 2, 3, 423, 54, 3232, -4, -554, 99932, 555]
heapq.heapify(nums)
print(nums)
print(heapq.heappop(nums))
print(heapq.heappop(nums))
print(heapq.heappop(nums))

輸出
[-554, 1, -4, 2, 54, 3232, 3, 423, 99932, 555]
-554
-4
1

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