Skip to content Skip to sidebar Skip to footer

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

  1. for each sub-list l in your library;
  2. forall terms t in search_terms;
  3. ifany of the strings s in l contains it;
  4. Keep l in the new list hits.

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"