The following Python code looks very long 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 method for writing this in Python, or am I just sticking to a long version?
Thank you for all the suggestions and explanations for the rationale for Python syntax.
After finding the following content on a numpy website, I think I found a solution that I like:
http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays
Applying the information from this website to my problem above will give you 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]
Then the following should work (but I don't have a Python interpreter to test):
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]