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

前端 未结 9 2115
栀梦
栀梦 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

提交回复
热议问题