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

后端 未结 10 1183
难免孤独
难免孤独 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条回答
  •  Happy的楠姐
    2021-01-02 15:56

    Here is a simplified version:

    def sublist(a,b):
        try:
            return a[0] in b and sublist(a[1:],b[1+b.index(a[0]):])
        except IndexError:
            return True
    
    >>> print sublist([1, 12, 3],[25, 1, 30, 12, 3, 40])
    True
    
    >>> print sublist([5, 90, 2],[90, 20, 5, 2, 17])
    False
    

提交回复
热议问题