How to print a sublist containing all the lines in another list?

search_terms = ['word','word 1','word 2']

library = [['desk','chair','lamp'],['cow','word','horse','word 2','word 1']]

I just want to be able to print all the lists in the library that contain ALL the words in search_terms. the search_terms list will not always have the same number of rows ...

Thanks to everyone who wants to help me!

+4
source share
1 answer

Use set.issubset:

>>> {'word','word 1','word 2'}.issubset(['desk','chair','lamp'])
False
>>> {'word','word 1','word 2'}.issubset(['cow','word','horse','word 2','word 1'])
True

>>> search_terms = ['word','word 1','word 2']
>>> library = [['desk','chair','lamp'],['cow','word','horse','word 2','word 1']]
>>> terms = set(search_terms)
>>> [x for x in library if terms.issubset(x)]
[['cow', 'word', 'horse', 'word 2', 'word 1']]
+6
source

All Articles