当来自Matlab背景时,以下Python代码似乎很长
>>> a = [1, 2, 3, 1, 2, 3]
>>> [index for index,value in enumerate(a) if value > 2]
[2, 5]
Run Code Online (Sandbox Code Playgroud)
在Matlab中我可以写:
>> a = [1, 2, 3, 1, 2, 3];
>> find(a>2)
ans =
3 6
Run Code Online (Sandbox Code Playgroud)
有没有用Python编写这个简短的方法,或者我只是坚持使用长版本?
感谢您对Python语法的基本原理的所有建议和解释.
在numpy网站上找到以下内容后,我想我找到了一个我喜欢的解决方案:
http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays
将该网站的信息应用于上述问题,将提供以下信息:
>>> from numpy import array
>>> a = array([1, 2, 3, 1, 2, 3])
>>> b = a>2
array([False, False, True, False, False, True], dtype=bool)
>>> r = array(range(len(b)))
>>> r(b)
[2, 5]
Run Code Online (Sandbox Code Playgroud)
以下应该可以工作(但我手头没有Python解释器来测试它):
class my_array(numpy.array):
def …Run Code Online (Sandbox Code Playgroud) python ×1