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?
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.
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.
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.
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 .
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With