在 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”等效的函数,但我目前无法访问这些库。