在Python中,如何在平面文件中搜索与特定数值最接近的匹配?

kau*_*hik 0 python

有格式的文件数据

3.343445 1  
3.54564 1  
4.345535 1  
2.453454 1
Run Code Online (Sandbox Code Playgroud)

等等多达1000行,我有给定的数字,如a=2.44443给定的文件,我需要找到文件中最接近给定数字的数字的行号"a"我怎么能这样做我现在正在做将整个文件加载到列表中并比较每个元素并找到最接近的一个更快更快的方法?

我的代码:我需要每次大约20000次对不同的文件使用这个,所以想要一个快速的方法

p=os.path.join("c:/begpython/wavnk/",str(str(str(save_a[1]).replace('phone','text'))+'.pm'))
        x=open(p , 'r')
        for i in range(6):
            x.readline()

        j=0
        o=[]
        for line in x:

            oj=str(str(line).rstrip('\n')).split(' ')
            o=o+[oj]

            j=j+1


        temp=long(1232332)
        end_time=save_a[4]

        for i in range((j-1)):
            diff=float(o[i][0])-float(end_time)
            if diff<0:
                diff=diff*(-1)
            if temp>diff:
                temp=diff
                pm_row=i
Run Code Online (Sandbox Code Playgroud)

Sil*_*ost 8

>>> gen = (float(line.partition(' ')[0]) for line in open(fname))
>>> min(enumerate(gen), key=lambda x: abs(x[1] - a))
(3, 2.453454)
Run Code Online (Sandbox Code Playgroud)