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

Time:11-19

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)

CodePudding user response:

You could use a regex (converting your template to a regex, then getting all matching words):

import re
template = ['_', '_', 'l', '_', '_']
words = ['hello', 'jacky', 'helps']
regexp = ''.join(template).replace('_','.')
# '..l..' in this case
match_words = [word for word in words if re.match(regexp,word)]

match_words
# Out[108]: ['hello', 'helps']

CodePudding user response:

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"]
  • Related