我有一个整数列表,我认为我可以使用np.searchsorted()进行二进制搜索以寻找最接近的整数。因此,我尝试过,
Python 3.6.9 (default, Nov 7 2019, 10:44:02)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> B = [0, 36, 75, 111, 162, 198, 237, 273]
>>> np.searchsorted(B, 210)
6
>>> B[np.searchsorted(B, 210)]
237
210的最近邻居应该不是198吗?有我想要的原生Python 3库吗?我可以自己实现,但是我正在寻找最快的实现。
我认为np.argmin()
适合您的目的。
尝试此代码。
import numpy as np
B = np.array([1,2,3,4,5])
criterion = 4
ind = np.argmin(np.abs(B - criterion)) # find the index i, where i'th element is the closest to criterion
print(B[ind])