在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]
Run Code Online (Sandbox Code Playgroud)
在Python中执行此操作的最佳方法是什么?
到目前为止,我已经提出以下建议.要获得值:
>>> a = [1,2,3,1,2,3,1,2,3]
>>> [val for val in a if val > 2]
[3, 3, 3]
Run Code Online (Sandbox Code Playgroud)
但是,如果我想要每个值的索引,它会更复杂一些:
>>> a = [1,2,3,1,2,3,1,2,3]
>>> inds = [i for (i, val) in enumerate(a) if val > 2]
>>> inds
[2, …Run Code Online (Sandbox Code Playgroud)