The following Python code appears to be very long winded when coming from a Matlab background
>>> a = [1, 2, 3, 1, 2, 3]
>>> [index for index,value in enumerate(a) if value > 2]
[2, 5]
When in Matlab I can write:
>> a = [1, 2, 3, 1, 2, 3];
>> find(a>2)
ans =
3 6
Is there a short hand method of writing this in Python, or do I just stick with the long version?
Thank you for all the suggestions and explanation of the rationale for Python's syntax.
After finding the following on the numpy website, I think I have found a solution I like:
http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays
Applying the information from that website to my problem above, would give the following:
>>> 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]
The following should then work (but I haven't got a Python interpreter on hand to test it):
class my_array(numpy.array):
def find(self, b):
r = array(range(len(b)))
return r(b)
>>> a = my_array([1, 2, 3, 1, 2, 3])
>>> a.find(a>2)
[2, 5]
See Question&Answers more detail:
os