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

后端 未结 10 1172
难免孤独
难免孤独 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:05

    How about this: let's approach this from the other side:

    def sublist(a,b):
        """returns True if a is contained in b and in the same order"""
        return a == [ch for ch in b if ch in a]
    

    This will fail in some circumstances (e.g. should [1,2,3] be a subset of [1,1,8,2,3]) but it's hard to say exactly how you want this implemented...

提交回复
热议问题