finding all sublists of list2 that are identical to list1

Klaus Neuner klaus_neuner82 at yahoo.de
Tue Feb 10 04:13:32 EST 2004


> def sublist(list1, list2):
>     len1 = len(list1)
>     rnge = xrange(len(list2))
>     return [i for i in rnge if list2[i:len1+i] == list1]

Thanks.

> but without more details, I'm
> shooting in the dark.

Actually, I want to leave open what list1 and list2 may contain. I
want to define a class Matcher, like so:

class Matcher(object):

    def match(self, a, b):
        if a == b:
            return True
        else:
            return False

    def all_matches(self, list1, list2):
        len1 = len(list1)
        rnge = xrange(len(list2))
        return [i for i in rnge if self.match(list2[i:len1+i], list1)]

I use the function "match" instead of "==" here, because I want to
make subclasses that use a different concept of equivalence. One type
of equivalence
could be "equality in the first element". 
    
class FirstElementMatcher(Matcher):

    def match(self, a, b):
        if a[0] == b[0]:
            return True
        else:
            return False



More information about the Python-list mailing list