Determine if all elements in a list are present and in the same order in another list

后端 未结 10 1220
难免孤独
难免孤独 2021-01-02 15:35

How do I create a function sublist() that takes two lists, list1 and list2, and returns True if list1 is a s

10条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-02 16:07

    Here's one way to do it in linear time (and constant space) with an iterator:

    def sublist(a, b):
        seq = iter(b)
        try:
            for x in a:
                while next(seq) != x: pass
            else:
                return True
        except StopIteration:
            pass
        return False
    

    Basically it goes through each element of the sublist, and sees if it can find that same element in the part of the complete list it hasn't looked at yet. If it makes it through the entire sublist it means we have a match (hence the else statement on the for loop). If we run out of elements to look at in the complete list, it means we don't have a match.

    Edit: I have updated my solution so it works with Python 3. For Python 2.5 and older, next(seq) needs to be replaced with seq.next().

提交回复
热议问题