Python: find a list within members of another list(in order)

前端 未结 9 2095
栀梦
栀梦 2020-12-03 10:40

If I have this:

a=\'abcdefghij\'
b=\'de\'

Then this finds b in a:

b in a => True

Is there a way of doi

9条回答
  •  眼角桃花
    2020-12-03 11:34

    This should work with whatever couple of lists, preserving the order. Is checking if b is a sub list of a

    def is_sublist(b,a): 
    
        if len(b) > len(a):
            return False    
    
        if a == b:
            return True    
    
        i = 0
        while i <= len(a) - len(b):
            if a[i] == b[0]:
                flag = True
                j = 1
                while i+j < len(a) and j < len(b):
                    if a[i+j] != b[j]:
                        flag = False
                    j += 1
                if flag:
                    return True
            i += 1
        return False
    

提交回复
热议问题