user3150759
user3150759

Reputation: 83

How to print a sublist that contains all of the strings 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 list(s) in library that contain ALL of the terms in search_terms. the list search_terms will not always have the same number of strings...

Thanks for anyone who is willing to help me!

Upvotes: 4

Views: 88

Answers (1)

falsetru
falsetru

Reputation: 368954

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']]

Upvotes: 6

Related Questions