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

前端 未结 9 2064
栀梦
栀梦 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:28

    I timed the accepted solution, my earlier solution and a new one with an index. The one with the index is clearly best.

    EDIT: I timed nosklo's solution, it's even much better than what I came up with. :)

    def is_sublist_index(a, b):
        if not a:
            return True
    
        index = 0
        for elem in b:
            if elem == a[index]:
                index += 1
                if index == len(a):
                    return True
            elif elem == a[0]:
                index = 1
            else:
                index = 0
    
        return False
    
    def is_sublist(a, b):
        return str(a)[1:-1] in str(b)[1:-1]
    
    def is_sublist_copylist(a, b):
        if a == []: return True
        if b == []: return False
        return b[:len(a)] == a or is_sublist_copylist(a, b[1:])
    
    from timeit import Timer
    print Timer('is_sublist([99999], range(100000))', setup='from __main__ import is_sublist').timeit(number=100)
    print Timer('is_sublist_copylist([99999], range(100000))', setup='from __main__ import is_sublist_copylist').timeit(number=100)
    print Timer('is_sublist_index([99999], range(100000))', setup='from __main__ import is_sublist_index').timeit(number=100)
    print Timer('sublist_nosklo([99999], range(100000))', setup='from __main__ import sublist_nosklo').timeit(number=100)
    

    Output in seconds:

    4.51677298546

    4.5824368

    1.87861895561

    0.357429027557

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-03 11:35

    Use the lists' string representation and remove the square braces. :)

    def is_sublist(a, b):
        return str(a)[1:-1] in str(b)
    

    EDIT: Right, there are false positives ... e.g. is_sublist([1], [11]). Crappy answer. :)

    0 讨论(0)
提交回复
热议问题