![](/img/trans.png)
[英]Find the smallest number that is greater than a given number in a sorted list
[英]given a sorted list, find the index of number
给定一个sorted list
和一个数字n
,以最有效(最快)的方式找到列表中n
之前的索引。
排序列表示例:
x_list = [1, 3.5, 5, 9.2, 20, 50.75]
数字n
,比如 n = 7.5
示例答案:列表中n
之前的值的索引是2
。
这是我到目前为止所尝试的:
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)
我可以比上述方法更快地找到吗?
注意:此列表已sorted
,而其他相同性质的问题unsorted
。
您可以使用bisect
执行二进制搜索:
import bisect
n = 7.5
index = bisect.bisect_left(x_list, n)-1
output: 2
注意。 如果目标在第一个索引之前,这将返回-1
,如果需要,您可以避免使用max(0, bisect.bisect_left(x_list, n)-1)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.