在Python,你是怎么找到的第一个值大于排序列表阈值的指数? [英] In Python, how do you find the index of the first value greater than a threshold in a sorted list?
本文介绍了在Python,你是怎么找到的第一个值大于排序列表阈值的指数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python中,你是怎么找到的第一个值的指数大于排序列表阈值?
In Python, how do you find the index of the first value greater than a threshold in a sorted list?
我能想到的做这个(线性搜索,手写的二分法,..)的几种方法,但我在寻找做一个干净的一个合理有效的方式。因为它可能是一个pretty的通病,我敢肯定,有经验的SOers可以帮助!
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!
谢谢!
推荐答案
看一看对开。
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
这篇关于在Python,你是怎么找到的第一个值大于排序列表阈值的指数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文