Printing a sublist containing all the lines in another list does not have to be 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 the lists in the library that contain ALL words in search_terms.

therefore, using the search_terms list above, the second sublist in the library will be printed, although the word 223 just contains the word, but is not a direct match.

I will not always have the same number of rows ...

Thanks to everyone who wants to help me!

and thanks to falsetru for helping me with my first question!

+2
source share
2 answers

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

It works as follows

  • foreach sub-list lin yours library;
  • for all t search_terms;
  • if any s l ;
  • l hits.
+3
>>> 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 in list(chain(*library))]
['cow', 'horse']
>>> [l for l in library if any(word for word in search_terms if word in l)]
[['cow', 'horse', 'word 223', 'barn']]
0

All Articles