Check for presence of a sliced list in Python

2019-01-01 11:12发布

I want to write a function that determines if a sublist exists in a larger list.

list1 = [1,0,1,1,1,0,0]
list2 = [1,0,1,0,1,0,1]

#Should return true
sublistExists(list1, [1,1,1])

#Should return false
sublistExists(list2, [1,1,1])

Is there a Python function that can do this?

标签: python list
10条回答
流年柔荑漫光年
2楼-- · 2019-01-01 11:44

Might as well throw in a recursive version of @NasBanov's solution

def foo(sub, lst):
    '''Checks if sub is in lst.

    Expects both arguments to be lists
    '''
    if len(lst) < len(sub):
        return False
    return sub == lst[:len(sub)] or foo(sub, lst[1:])
查看更多
千与千寻千般痛.
3楼-- · 2019-01-01 11:47

No function that I know of

def sublistExists(list, sublist):
    for i in range(len(list)-len(sublist)+1):
        if sublist == list[i:i+len(sublist)]:
            return True #return position (i) if you wish
    return False #or -1

As Mark noted, this is not the most efficient search (it's O(n*m)). This problem can be approached in much the same way as string searching.

查看更多
浪荡孟婆
4楼-- · 2019-01-01 11:51

Simply create sets from the two lists and use the issubset function:

def sublistExists(big_list, small_list):
    return set(small_list).issubset(set(big_list))
查看更多
余生无你
5楼-- · 2019-01-01 11:52

Here is a way that will work for simple lists that is slightly less fragile than Mark's

def sublistExists(haystack, needle):
    def munge(s):
        return ", "+format(str(s)[1:-1])+","
    return munge(needle) in munge(haystack)
查看更多
残风、尘缘若梦
6楼-- · 2019-01-01 11:52
def sublistExists(x, y):
  occ = [i for i, a in enumerate(x) if a == y[0]]
  for b in occ:
      if x[b:b+len(y)] == y:
           print 'YES-- SUBLIST at : ', b
           return True
      if len(occ)-1 ==  occ.index(b):
           print 'NO SUBLIST'
           return False

list1 = [1,0,1,1,1,0,0]
list2 = [1,0,1,0,1,0,1]

#should return True
sublistExists(list1, [1,1,1])

#Should return False
sublistExists(list2, [1,1,1])
查看更多
怪性笑人.
7楼-- · 2019-01-01 11:52
def sublist(l1,l2):
  if len(l1) < len(l2):
    for i in range(0, len(l1)):
      for j in range(0, len(l2)):
        if l1[i]==l2[j] and j==i+1:
        pass
      return True
  else:
    return False
查看更多
登录 后发表回答