【问题标题】:Am I using np.searchsorted() right?我使用 np.searchsorted() 对吗?
【发布时间】:2020-04-12 10:30:28
【问题描述】:

我有一个整数列表,我想我可以使用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 库可以满足我的需求?我可以自己实现它,但我正在寻找最快的实现。

【问题讨论】:

    标签: python-3.x numpy binary-search


    【解决方案1】:

    我认为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])
    

    【讨论】:

      猜你喜欢
      • 2015-06-01
      • 1970-01-01
      • 2021-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多