Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find sub list inside a list in python

Tags:

python

I have a list of numbers

l = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0]
[0, 0, 2, 1, 1, 2, 0, 0, 0, 0]
[0, 0, 2, 1, 1, 2, 2, 0, 0, 1]
[0, 0, 1, 2, 2, 0, 1, 0, 0, 2]
[1, 0, 1, 1, 1, 2, 1, 0, 2, 1]]

For example , i have to search a pattern '2,1,1,2' , as we can see that is present in row 6 and 7 . in order to find that sequence i tried converting each list into str and tried to search the pattern , but for some reason the code isnt working.

import re
for i in l:
 if re.search('2,1,1,2' , str(i).strip('[').strip(']')): print " pattern found"

am i missing something in here ?

like image 561
Rahul Avatar asked Dec 12 '25 15:12

Rahul


2 Answers

Converting your list in string is really not a good idea.

How about something like this:

def getsubidx(x, y):
    l1, l2 = len(x), len(y)
    for i in range(l1):
        if x[i:i+l2] == y:
            return i
like image 165
cJ Zougloub Avatar answered Dec 14 '25 06:12

cJ Zougloub


I suggest you to use the Knuth-Morris-Pratt algorithm. I suppose you are implicitly assuming that your pattern is present in the list just one time, or you are just interested in knowing if it's in or not.

If you want the list of each first element which starts the sequence, then you can use KMP. Think about it as a sort of string.find() for lists.

I hope this will help.

like image 30
user_1177868 Avatar answered Dec 14 '25 07:12

user_1177868



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!