'How to check if a list partially matches one of the lists in a list of lists?
I would like to check if a list is a sublist if a bigger list of lists. It would be easy to check if it is just in the list of lists but a partial match is also acceptable.
In this example it should return True
:
list = [1,4,9]
listoflists = [[1,2,3], [1,3,4,7,9], [6,8]]
Any ideas?
Solution 1:[1]
Below example works by:
- Iterating over each sublist within
lol
- Generating a list representing the intersection of the current sublist and
lol
(stored each iteration astemp
) - Comparing
sorted()
versions oftemp
andl
, returningTrue
if a match is found. - Returning
False
if all sublists are checked with no match found
The function will return True
if either a full match is found between elements of l
and any sublist of lol
, or in "partial match" cases in which all elements of l
are present within any sublist of lol
.
def compare_sublists(l, lol):
for sublist in lol:
temp = [i for i in sublist if i in l]
if sorted(temp) == sorted(l):
return True
return False
Solution 2:[2]
The following should work:
any([all([list.count(i)<=x.count(i) for i in list]) for x in listoflists])
Solution 3:[3]
from itertools import repeat
def is_sub_list(a, b):
if [] in (a, b):
return False
c = set(a)
d = map(set, b)
return True if any(map(set.issubset, repeat(c), d)) else False
lst1 = [1, 3, 9]
lst2 = [1, 3, 8]
lst_of_lst = [[1, 2, 3], [1, 3, 4, 7, 9], [6, 8]]
print(is_sub_list(lst1, lst_of_lst)) # True
print(is_sub_list(lst2, lst_of_lst)) # False
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | Jason Yang |