【发布时间】:2011-08-29 06:31:03
【问题描述】:
我有一个值数组 t,它总是按递增顺序排列(但并不总是均匀间隔)。我有另一个值,x。我需要找到 t 中的索引,使得 t[index] 最接近 x。对于 x t.max(),函数必须返回最大索引(或 -1)。
我已经编写了两个函数来做到这一点。第一个,f1,在这个简单的计时测试中要快得多。但我喜欢第二个只是一条线。此计算将在一个大型数组上完成,可能每秒多次。
谁能想出一些其他功能与第一个功能相当的时间但看起来更干净的代码?比第一个更快的东西怎么样(速度是最重要的)?
谢谢!
代码:
import numpy as np
import timeit
t = np.arange(10,100000) # Not always uniform, but in increasing order
x = np.random.uniform(10,100000) # Some value to find within t
def f1(t, x):
ind = np.searchsorted(t, x) # Get index to preserve order
ind = min(len(t)-1, ind) # In case x > max(t)
ind = max(1, ind) # In case x < min(t)
if x < (t[ind-1] + t[ind]) / 2.0: # Closer to the smaller number
ind = ind-1
return ind
def f2(t, x):
return np.abs(t-x).argmin()
print t, '\n', x, '\n'
print f1(t, x), '\n', f2(t, x), '\n'
print t[f1(t, x)], '\n', t[f2(t, x)], '\n'
runs = 1000
time = timeit.Timer('f1(t, x)', 'from __main__ import f1, t, x')
print round(time.timeit(runs), 6)
time = timeit.Timer('f2(t, x)', 'from __main__ import f2, t, x')
print round(time.timeit(runs), 6)
【问题讨论】:
-
由于您的数组已排序,请尝试二进制搜索。查看这个问题的答案:stackoverflow.com/questions/212358/binary-search-in-python
-
我刚下班,但想稍后再看。我认为一旦你测试了 x max(t),你可以通过短路来改进你的第一个函数,但我还没有机会测试它。跨度>
标签: python performance indexing numpy