Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to know if a list of elements is on a larger list without using 'in' keyword?

Tags:

python

I want to do this. I have two python lists, one larger than the other and I want to know is there is a way to check if the elements of the smaller list are in the big list in the exact same order for example:

small_list = [4,2,5]
big_list = [1,2,5,7,2,4,2,5,67,8,5,13,45]

I tried using the in keyword but It did not worked :'(

like image 812
Fitoria Avatar asked Dec 01 '22 11:12

Fitoria


2 Answers

def in_list(small, big):
    l_sml = len(small)
    l_big = len(big)
    return any((big[i:i+l_sml]==small for i in xrange(l_big-l_sml+1)))

print in_list([4,2,1], [1,2,3,4,2,1,0,5]) # True
print in_list([1,2,3], [1,2,4])           # False
like image 73
ChristopheD Avatar answered Dec 05 '22 07:12

ChristopheD


Hmm, maybe it's overkill, but you can use the SequenceMatcher class from difflib:

from difflib import SequenceMatcher 
small_list = [4,2,5]
big_list = [1,2,5,7,2,4,2,5,67,8,5,13,45]
print SequenceMatcher(None, small_list, big_list).get_matching_blocks()

difflib documentation

like image 23
ephes Avatar answered Dec 05 '22 07:12

ephes