Print A Sublist That Contains All Strings In Another List, Without Necessarily Being A Direct Match
search_terms = ['word','cow','horse'] library = [['desk','chair','lamp'],['cow','horse','word 223','barn']] I want to be able to print all list(s) in library that contain ALL of
Solution 1:
To get your hits, use a list comprehension:
search_terms = ['word', 'cow', 'horse']
library = [['desk', 'chair', 'lamp'],
['cow', 'horse', 'word 223', 'barn']]
hits = [l for l in library if
all(any(t in s for s in l)
for t in search_terms)]
This works as follows
for
each sub-listl
in yourlibrary
;for
all
termst
insearch_terms
;if
any
of the stringss
inl
contains it;- Keep
l
in the new listhits
.
Solution 2:
>>> search_terms = ['word','cow','horse']
>>> library = [['desk','chair','lamp'],['cow','horse','word 223','barn']]
>>> from itertools import chain
>>> list(chain(*library))
['desk', 'chair', 'lamp', 'cow', 'horse', 'word 223', 'barn']
>>> [word for word in search_terms if word inlist(chain(*library))]
['cow', 'horse']
>>> [l for l in library ifany(word for word in search_terms if word in l)]
[['cow', 'horse', 'word 223', 'barn']]
Post a Comment for "Print A Sublist That Contains All Strings In Another List, Without Necessarily Being A Direct Match"