[英]given a sorted list, find the index of number
Given a sorted list
and a number n
, find the index in the list that precedes n
in the most efficient (fastest) way.给定一个
sorted list
和一个数字n
,以最有效(最快)的方式找到列表中n
之前的索引。
sorted list example:排序列表示例:
x_list = [1, 3.5, 5, 9.2, 20, 50.75]
number n
, say n = 7.5数字
n
,比如 n = 7.5
Example answer: the index of the value in the list that precedes n
is 2
.示例答案:列表中
n
之前的值的索引是2
。
This is what i have tried so far:这是我到目前为止所尝试的:
x_list = [1, 3.5, 5, 9.2, 20, 50.75]
n = 7.5
for i, v in enumerate(x_list):
if v < n: xlow = i
else: break
print(xlow)
Can i do a quicker find than the above method?我可以比上述方法更快地找到吗?
Note: This list is sorted
whereas other questions of the same nature are unsorted
.注意:此列表已
sorted
,而其他相同性质的问题unsorted
。
You can use bisect
to perform a binary search:您可以使用
bisect
执行二进制搜索:
import bisect
n = 7.5
index = bisect.bisect_left(x_list, n)-1
output: 2
output:
2
NB.注意。 In case the target is before the first index, this will return
-1
, which you can avoid using max(0, bisect.bisect_left(x_list, n)-1)
if needed.如果目标在第一个索引之前,这将返回
-1
,如果需要,您可以避免使用max(0, bisect.bisect_left(x_list, n)-1)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.