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

前端 未结 9 2118
栀梦
栀梦 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 think this will be faster - It uses C implementation list.index to search for the first element, and goes from there on.

    def find_sublist(sub, bigger):
        if not bigger:
            return -1
        if not sub:
            return 0
        first, rest = sub[0], sub[1:]
        pos = 0
        try:
            while True:
                pos = bigger.index(first, pos) + 1
                if not rest or bigger[pos:pos+len(rest)] == rest:
                    return pos
        except ValueError:
            return -1
    
    data = list('abcdfghdesdkflksdkeeddefaksda')
    print find_sublist(list('def'), data)
    

    Note that this returns the position of the sublist in the list, not just True or False. If you want just a bool you could use this:

    def is_sublist(sub, bigger): 
        return find_sublist(sub, bigger) >= 0
    

提交回复
热议问题