Search code examples
pythonlistloopsif-statementnested-lists

Check if a word exists at a particular position of a list


Suppose I have a list of lists.

List1=[["Red is my favorite color."],["Blue is her favorite."], ["She is really nice."]]

Now I want to check if the word 'is' exists after a certain set of words.

I made a word lise word_list=['Red', 'Blue']

Is there a way to check that using if statement?

If I write if 'is' in sentences: It will return all three sentences in List1, I want it to return first two sentences.

Is there a way to check if the word 'is' is positioned exactly after the words in word_list? Thank you in advance.


Solution

  • NB. I assumed a match in the start of the string. For a match anywhere use re.search instead of re.match.

    You can use a regex:

    import re
    
    regex = re.compile(fr'\b({"|".join(map(re.escape, word_list))})\s+is\b')
    # regex: \b(Red|Blue)\s+is\b
    
    out = [[bool(regex.match(x)) for x in l]
           for l in List1]
    

    Output: [[True], [True], [False]]

    Used input:

    List1 = [['Red is my favorite color.'],
             ['Blue is her favorite.'],
             ['She is really nice.']]
    
    word_list = ['Red', 'Blue']
    

    If you want the sentences:

    out = [[x for x in l if regex.match(x)]
           for l in List1]
    

    Output:

    [['Red is my favorite color.'],
     ['Blue is her favorite.'],
     []]
    

    Or as flat list:

    out = [x for l in List1 for x in l if regex.match(x)]
    

    Output:

    ['Red is my favorite color.',
     'Blue is her favorite.']