Search code examples
pythonlistloopsfor-loopcomparison

How can I compare this template list to a list of words?


I'm trying to find out which words fit into this template but don't know how to compare them. Is there any way to do this without counting specific alphabetic characters in the template, getting their indices, and then checking each letter in each word?

The desired output is a list of words from words that fit the template.

alist = []
template = ['_', '_', 'l', '_', '_']
words = ['hello', 'jacky', 'helps']
if (word fits template):
    alist.append(word)

Solution

  • You can use zip to compare the word to template:

    def word_fits(word, template):
        if len(word) != len(template):
            return False
    
        for w, t in zip(word, template):
            if t != "_" and w != t:
                return False
    
        return True
    
    
    template = ["_", "_", "l", "_", "_"]
    words = ["hello", "jacky", "helps"]
    
    alist = [w for w in words if word_fits(w, template)]
    
    print(alist)
    

    Prints:

    ["hello", "helps"]