Python 中的 MATLAB 风格的 find() 函数 [英] MATLAB-style find() function in Python
问题描述
在 MATLAB 中很容易找到满足特定条件的值的索引:
<代码>>>a = [1,2,3,1,2,3,1,2,3];>>find(a > 2) % 找到满足此条件的指数[3, 6, 9] %(MATLAB 使用基于 1 的索引)>>a(find(a > 2)) % 获取这些位置的值[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]>>>工业[2, 5, 8]>>>[val for (i, val) in enumerate(a) if i in inds][3, 3, 3]在 Python 中是否有更好的方法来执行此操作,尤其是对于任意条件(不仅仅是 'val > 2')?
我在 NumPy 中找到了与 MATLAB 'find' 等效的函数,但我目前无法访问这些库.
您可以创建一个函数,该函数接受一个可调用参数,该参数将用于列表推导式的条件部分.然后您可以使用 lambda 或其他函数对象来传递您的任意条件:
def 索引(a, func):返回 [i for (i, val) in enumerate(a) if func(val)]a = [1, 2, 3, 1, 2, 3, 1, 2, 3]inds = 指数(a, lambda x: x > 2)>>>工业[2, 5, 8]
它更接近您的 Matlab 示例,无需加载所有 numpy.
In MATLAB it is easy to find the indices of values that meet a particular condition:
>> 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]
What would be the best way to do this in Python?
So far, I have come up with the following. To just get the values:
>>> a = [1,2,3,1,2,3,1,2,3]
>>> [val for val in a if val > 2]
[3, 3, 3]
But if I want the index of each of those values it's a bit more complicated:
>>> 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]
Is there a better way to do this in Python, especially for arbitrary conditions (not just 'val > 2')?
I found functions equivalent to MATLAB 'find' in NumPy but I currently do not have access to those libraries.
You can make a function that takes a callable parameter which will be used in the condition part of your list comprehension. Then you can use a lambda or other function object to pass your arbitrary condition:
def indices(a, func):
return [i for (i, val) in enumerate(a) if func(val)]
a = [1, 2, 3, 1, 2, 3, 1, 2, 3]
inds = indices(a, lambda x: x > 2)
>>> inds
[2, 5, 8]
It's a little closer to your Matlab example, without having to load up all of numpy.
这篇关于Python 中的 MATLAB 风格的 find() 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!