python - How to get the index of a list items in another list? -




consider have these lists:

l = [5,6,7,8,9,10,5,15,20] m = [10,5] 

i want index of m in l. used list comprehension that:

[(i,i+1) i,j in enumerate(l) if m[0] == l[i] , m[1] == l[i+1]] 

output : [(5,6)]

but if have more numbers in m, feel not right way. there easy approach in python or numpy?

another example:

l = [5,6,7,8,9,10,5,15,20,50,16,18] m = [10,5,15,20] 

the output should be:

[(5,6,7,8)] 

you looking starting indices of list in list.

approach #1 : 1 approach solve create sliding windows of elements in list in searching, giving 2d array , use numpy broadcasting perform broadcasted comparison against search list against each row of 2d sliding window version obtained earlier. thus, 1 method -

# strided_app https://stackoverflow.com/a/40085052/ def strided_app(a, l, s ):  # window len = l, stride len/stepsize = s     nrows = ((a.size-l)//s)+1     n = a.strides[0]     return np.lib.stride_tricks.as_strided(a, shape=(nrows,l), strides=(s*n,n))  def pattern_index_broadcasting(all_data, search_data):     n = len(search_data)     all_data = np.asarray(all_data)     all_data_2d = strided_app(np.asarray(all_data), n, s=1)     return np.flatnonzero((all_data_2d == search_data).all(1))  out = np.squeeze(pattern_index_broadcasting(l, m)[:,none] + np.arange(len(m))) 

sample runs -

in [340]: l = [5,6,7,8,9,10,5,15,20,50,16,18]      ...: m = [10,5,15,20]      ...:   in [341]: np.squeeze(pattern_index_broadcasting(l, m)[:,none] + np.arange(len(m))) out[341]: array([5, 6, 7, 8])  in [342]: l = [5,6,7,8,9,10,5,15,20,50,16,18,10,5,15,20]      ...: m = [10,5,15,20]      ...:   in [343]: np.squeeze(pattern_index_broadcasting(l, m)[:,none] + np.arange(len(m))) out[343]:  array([[ 5,  6,  7,  8],        [12, 13, 14, 15]]) 

approach #2 : method sliding window , row-wise scalar view data search data , data search for, giving 1d data work with, -

# view1d https://stackoverflow.com/a/45313353/ def view1d(a, b): # a, b arrays     = np.ascontiguousarray(a)     void_dt = np.dtype((np.void, a.dtype.itemsize * a.shape[1]))     return a.view(void_dt).ravel(),  b.view(void_dt).ravel()  def pattern_index_view1d(all_data, search_data):     = strided_app(np.asarray(all_data), l=len(search_data), s=1)     a0v, b0v = view1d(np.asarray(a), np.asarray(search_data))     return np.flatnonzero(np.in1d(a0v, b0v))   out = np.squeeze(pattern_index_view1d(l, m)[:,none] + np.arange(len(m))) 




wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -