Python 中的 MATLAB 风格的 find() 函数

2024-04-09

在 MATLAB 中,很容易找到满足特定条件的值的索引:

>> a = [1,2,3,1,2,3,1,2,3];
>> find(a > 2)     % find the indecies where this condition is true
[3, 6, 9]          % (MATLAB uses 1-based indexing)
>> a(find(a > 2))  % get the values at those locations
[3, 3, 3]

在 Python 中执行此操作的最佳方法是什么?

到目前为止,我已经提出了以下建议。只获取值:

>>> a = [1,2,3,1,2,3,1,2,3]
>>> [val for val in a if val > 2]
[3, 3, 3]

但如果我想要每个值的索引,那就有点复杂了:

>>> a = [1,2,3,1,2,3,1,2,3]
>>> inds = [i for (i, val) in enumerate(a) if val > 2]
>>> inds
[2, 5, 8]
>>> [val for (i, val) in enumerate(a) if i in inds]
[3, 3, 3]

在 Python 中是否有更好的方法来做到这一点,特别是对于任意条件(不仅仅是“val > 2”)?

我在 NumPy 中找到了与 MATLAB“find”等效的函数,但我目前无法访问这些库。


在 numpy 中你有where :

>> import numpy as np
>> x = np.random.randint(0, 20, 10)
>> x
array([14, 13,  1, 15,  8,  0, 17, 11, 19, 13])
>> np.where(x > 10)
(array([0, 1, 3, 6, 7, 8, 9], dtype=int64),)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 中的 MATLAB 风格的 find() 函数 的相关文章

随机推荐