Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if list is a sublist

Tags:

python

I need to check if list1 is a sublist of list2 (True; if every integer in list2 that is common with list1 is in the same order of indexes as in list1)

def sublist(lst1,lst2):     for i in range(len(lst1)):         if lst1[i] not in lst2:             return False         for j in range(len(lst2)):             if (lst1[j] in lst2) and (lst2.index(lst1[i+1]) > lst2.index(lst1[i])):                 return True 

Can anybody help me... why isn't this working?

like image 483
MMM Avatar asked Mar 12 '16 22:03

MMM


People also ask

How do you check if a list is a sublist?

issubset() function. The most used and recommended method to check for a sublist. This function is tailor made to perform the particular task of checking if one list is a subset of another.

How do you check if a list is a sublist in Java?

You can use method Collections. indexOfSubList . Returns the starting position of the first occurrence of the specified target list within the specified source list, or -1 if there is no such occurrence. More formally, returns the lowest index i such that source.

Is list a sublist?

Show activity on this post. List A is a sublist of list B if the exact sequence of elements of A exists in B. An empty list is a sublist of any list.

How do you check if something is a subset in Python?

Python Set issubset() The issubset() method returns True if set A is the subset of B , i.e. if all the elements of set A are present in set B . Else, it returns False .


2 Answers

i need to check if list1 is a sublist to list2 (True; if every integer in list2 that is common with list1 is in the same order of indexes as in list1)

Your code isn't working because as soon as a list element in ls1 doesn't occur in ls2 it will return False immediately.

This creates two lists that contain only the common elements (but in their original order) and then returns True when they are the same:

def sublist(lst1, lst2):    ls1 = [element for element in lst1 if element in lst2]    ls2 = [element for element in lst2 if element in lst1]    return ls1 == ls2 

edit: A memory-efficient variant:

def sublist(ls1, ls2):     '''     >>> sublist([], [1,2,3])     True     >>> sublist([1,2,3,4], [2,5,3])     True     >>> sublist([1,2,3,4], [0,3,2])     False     >>> sublist([1,2,3,4], [1,2,5,6,7,8,5,76,4,3])     False     '''     def get_all_in(one, another):         for element in one:             if element in another:                 yield element      for x1, x2 in zip(get_all_in(ls1, ls2), get_all_in(ls2, ls1)):         if x1 != x2:             return False      return True 
like image 62
L3viathan Avatar answered Sep 18 '22 18:09

L3viathan


An easy way to check if all elements of a list are in other one is converting both to sets:

def sublist(lst1, lst2):     return set(lst1) <= set(lst2) 
like image 37