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

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