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 :'(
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With