我想找出哪些词适合这个模板,但不知道如何比较它们。有没有办法做到这一点,而不计算模板中的特定字母字符,获得它们的索引,然后检查每个单词中的每个字母?
期望的输出是符合模板的单词列表。
alist = []
template = ['_', '_', 'l', '_', '_']
words = ['hello', 'jacky', 'helps']
if (word fits template):
alist.append(word)
您可以使用zip
将单词与模板进行比较:
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)
打印:
["hello", "helps"]
您可以使用正则表达式(将模板转换为正则表达式,然后获得所有匹配的单词):
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']