高效地在 Python 列表中查找索引(与 MATLAB 相比)

2024-03-23

我很难找到一种有效的解决方案来在 Python 列表中查找索引。到目前为止,我测试过的所有解决方案都比 MATLAB 中的“查找”函数慢。我刚刚开始使用Python(因此,我的经验不是很丰富)。

在 MATLAB 中我将使用以下内容:

a = linspace(0, 1000, 1000); % monotonically increasing vector
b = 1000 * rand(1, 100); % 100 points I want to find in a
for i = 1 : numel(b)
    indices(i) = find(b(i) <= a, 1); % find the first index where b(i) <= a
end

如果我使用 MATLAB 的 arrayfun(),我可以稍微加快这个过程。 在Python中我尝试了几种可能性。我用了

for i in xrange(0, len(b)):
   tmp = numpy.where(b[i] <= a)
   indices.append(tmp[0][0])

这需要很多时间,特别是当 a 很大时。 如果 b 已排序,我可以使用

for i in xrange(0, len(b)):
    if(b[curr_idx] <= a[i]):
        indices.append(i)
        curr_idx += 1
    if(curr_idx >= len(b)):
        return indices
        break

这比 numpy.where() 解决方案快得多,因为我只需搜索列表一次,但这仍然比 MATLAB 解决方案慢。

有人能提出更好/更有效的解决方案吗? 提前致谢。


Try numpy.searchsorted:

>> a = np.array([0, 1, 2, 3, 4, 5, 6, 7])
>> b = np.array([1, 2, 4, 3, 1, 0, 2, 9])
% sorting b "into" a
>> np.searchsorted(a, b, side='right')-1
array([1, 2, 4, 3, 1, 0, 2, 9])

您可能需要对 b 中超出 a 范围的值进行一些特殊处理 - 例如上例中的 9。 尽管如此,这应该比任何基于循环的方法更快。

作为旁白: 相似地,histc在 MATLAB 中会比循环快得多。

EDIT:

如果你想得到索引在哪里b最接近a,您应该能够使用相同的代码,只需修改一下 a:

>> a_mod = 0.5*(a[:-1] + a[1:]) % take the centers between the elements in a
>> np.searchsorted(a_mod, np.array([0.9, 2.1, 4.2, 2.9, 1.1]), side='right')
array([1, 2, 4, 3, 1])

请注意,您可以删除-1 since a_mod有一个元素小于a.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

高效地在 Python 列表中查找索引(与 MATLAB 相比) 的相关文章

随机推荐