这可能是一个特殊情况,但你应该能够使用numpy
digitize.这里需要注意的是,垃圾箱必须单调减少或增加.
>>> import numpy
>>> a = numpy.array([10,7,2,0])
>>> b = numpy.array([10,9,8,7,6,5,4,3,2,1])
>>> indices = [numpy.where(a<=x)[0][0] for x in b]
[0, 1, 1, 1, 2, 2, 2, 2, 2, 3]
>>> numpy.digitize(b,a)
array([0, 1, 1, 1, 2, 2, 2, 2, 2, 3])
定时测试的设置:
a = np.arange(50)[::-1]
b = np.random.randint(0,50,1E3)
np.allclose([np.where(a<=x)[0][0] for x in b],np.digitize(b,a))
Out[55]: True
一些时间:
%timeit [np.where(a<=x)[0][0] for x in b]
100 loops, best of 3: 4.97 ms per loop
%timeit np.digitize(b,a)
10000 loops, best of 3: 48.1 µs per loop
看起来加速了两个数量级,但这在很大程度上取决于箱的数量.你的时间会有所不同.
为了与Jamie的回答进行比较,我已经计算了以下两段代码.由于我主要想关注搜索和数字化的速度,我稍微减少了Jam