python - Return values from a list where difference != 2 -


i have list e.g. my_list = [1, 3, 5, 7, 14, 16, 18, 22, 28, 30, 32, 41, 43]

i want function return values list difference between value , previous value not equal 2, e.g. function return [1, 14, 22, 28, 41] above list. note first value of my_list appear first value of output. input lists of non-zero length , order of 100's.

so far have this:

def get_output(array):     start = [array[0]]     in range(1, len(array)-1):         if (array[i] - array[i-1]) != 2:             start.append(array[i])      return start 

is there vectorised solution faster, bearing in mind applying function thousands of input arrays?

to avoid using inefficient np.concat, use np.ediff1 instead of np.diff, takes to_begin argument pre-pend result:

>>> my_list = [1, 3, 5, 7, 14, 16, 18, 22, 28, 30, 32, 41, 43] >>> arr = np.array(my_list) >>> np.ediff1d(arr, to_begin=0) array([0, 2, 2, 2, 7, 2, 2, 4, 6, 2, 2, 9, 2]) 

so now, using boolean-indexing:

>>> arr[np.ediff1d(arr, to_begin=0) != 2] array([ 1, 14, 22, 28, 41]) 

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -