在长排序列表中搜索值之前和之后

DGT*_*DGT 5 python

什么是在长排序列表中搜索数字(例如12.31)的最快方法,并且当未找到确切值时,在我的"搜索"值之前和之后获取值(例如,列表中的11.12和12.03)下面)?
提前谢谢了.

long_list = [10.11, 11.12, 13.03, 14.2 .. 12345.67]
Run Code Online (Sandbox Code Playgroud)

Fre*_*ihl 5

最快可能是使用 python 中的内置支持。在这里我正在考虑二等分模块。下面我使用字典快速检查某个值是否在列表中,时间复杂度为 O(1);如果不是,bisect则用于查找小于和大于所查找值的值。

#!/usr/bin/env python

import bisect

def find_lt(a, x):
    'Find rightmost value less than x'
    i = bisect.bisect_left(a, x)
    if i:
        return a[i-1]
    raise ValueError

def find_gt(a, x):
    'Find leftmost value greater than x'
    i = bisect.bisect_right(a, x)
    if i != len(a):
        return a[i]
    raise ValueError

# First create a test-list (49996 items)
i=1.0
R=[1.0]
D={}
while i < 10000:
    i+=0.2
    i=round(i,2)
    D[i]=True
    R.append(i)

# Locate a value, in this case 100.3 which is not in the list
x=100.3
if D.has_key(x):
    print "found", x
else:
    print find_lt(R, x)
    print find_gt(R, x)
Run Code Online (Sandbox Code Playgroud)

输出x=100.3

100.2
100.4
Run Code Online (Sandbox Code Playgroud)