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

后端 未结 10 1173
难免孤独
难免孤独 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 15:44

    Here's another solution that may be easier for novices to understand than Hetman's. (Notice that it's very close to the OP's implementation in this duplicate question, but avoiding the problem of restarting the search from the start of b each time.)

    def sublist(a, b):
        i = -1
        try:
            for e in a:
                i = b.index(e, i+1)
        except ValueError:
            return False
        else:
            return True
    

    Of course this requires b to be a list, while Hetman's answer allows any iterable. And I think that (for people who understand Python well enough) it's less simple than Hetman's answer, too.

    Algorithmically, it's doing the same thing as Hetman's answer, so it's O(N) time and O(1) space. But practically, it may be faster, at least in CPython, since we're moving the inner loop from a Python while around an iterator to a C fast-getindex loop (inside list.index). Then again, it may be slower, because we're copying around that i value instead of having all state embedded inside a (C-implemented) iterator. If it matters, test them both with your real data. :)

提交回复
热议问题