Python中的MATLAB风格的find()函数 [英] MATLAB-style find() function in Python

查看:465
本文介绍了Python中的MATLAB风格的find()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

$ $ $ $ $ $ $ $ $ $ $& a = [1,2,3,1,2,3,1,2,3];
>> find(a> 2)%找到这个条件为真的indecies
[3,6,9]%(MATLAB使用基于1的索引)
>> a(find(a> 2))%得到这些位置的值
[3,3,3]

在Python中这样做的最好方法是什么?



到目前为止,我已经提出了以下内容。要获取值:

 >>> a = [1,2,3,1,2,3,1,2,3] 
>>> val中val的值,如果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]
>>> (a)如果我在工作中]
[3,3,3]

有没有更好的方法来做到这一点在Python中,尤其是对于任意条件(而不是'val> 2')?

我发现函数相当于NumPy中的MATLAB'find',但我目前无法访问那些库。 解决方案

您可以创建一个函数它需要一个可调用的参数,这个参数将在列表理解的条件部分使用。然后,您可以使用 lambda 或其他函数对象来传递任意条件:
$ b $ pre $ code $ def $ index $ $ b $ return )if func(val)]

a = [1,2,3,1,2,3,1,2,3]

inds = indices(a,lambda x:x> 2)

>>> inds
[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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆