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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值