python二分法排序,在Python,你是怎么找到的第一个值大于排序列表阈值的指数?...

这篇博客讨论了如何在Python中高效地找出已排序列表中第一个大于特定阈值的元素的索引。作者比较了几种方法,包括线性搜索和二分查找,并使用`bisect`模块展示了简洁且高效的解决方案。此外,还通过`timeit`模块对比了不同方法的执行速度,显示了二分查找在性能上的优势。
摘要由CSDN通过智能技术生成

In Python, how do you find the index of the first value greater than a threshold in a sorted list?

I can think of several ways of doing this (linear search, hand-written dichotomy,..), but I'm looking for a clean an reasonably efficient way of doing it. Since it's probably a pretty common problem, I'm sure experienced SOers can help!

Thanks!

解决方案

Have a look at bisect.

import bisect

l = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

bisect.bisect(l, 55) # returns 7

Compare it with linear search:

timeit bisect.bisect(l, 55)

# 375ns

timeit next((i for i,n in enumerate(l) if n > 55), len(l))

# 2.24us

timeit next((l.index(n) for n in l if n > 55), len(l))

# 1.93us

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值