首页 > 解决方案 > 检查模式是否在单词列表中

问题描述

我需要一个包含与模式完全相同的单词的输出 - 仅在相同位置的相同字母(并且字母不应在其他地方的单词中显示)和相同的长度,例如:

words = ['hatch','catch','match','chat','mates'] 
pattern = '_atc_

需要的输出:

['hatch','match']

我曾尝试使用嵌套的 for 循环,但它不适用于以 '_' 开头和结尾的模式

def filter_words_list(words, pattern):
relevant_words = []
for word in words:
    if len(word) == len(pattern):
        for i in range(len(word)):
            for j in range(len(pattern)):
                if word[i] != pattern[i]:
                    break
                if word[i] == pattern[i]:
                    relevant_words.append(word)

谢谢 !

标签: pythonlist

解决方案


您可以使用正则表达式

import re

words = ['hatch','catch','match','chat','mates']
pattern = re.compile('[^atc]atc[^atc]')

result = list(filter(pattern.fullmatch, words))
print(result)

输出

['hatch', 'match']

该模式'[^atc]atc[^atc]'匹配所有不是 a 或 t 或 c ( [^atc]) 的'atc'内容,然后再匹配所有不是 a 或 t 或 c 的内容。

作为替代方案,您可以编写自己的匹配函数,该函数适用于任何给定的模式:

from collections import Counter


def full_match(word, pattern='_atc_'):
    if len(pattern) != len(word):
        return False

    pattern_letter_counts = Counter(e for e in pattern if e != '_')  # count characters that are not wild card
    word_letter_counts = Counter(word) # count letters

    if any(count != word_letter_counts.get(ch, 0) for ch, count in pattern_letter_counts.items()):
        return False

    return all(p == w for p, w in zip(pattern, word) if p != '_')  # the word must match in all characters that are not wild card


words = ['hatch', 'catch', 'match', 'chat', 'mates']


result = list(filter(full_match, words))
print(result)

输出

['hatch', 'match']

更远

  1. 请参阅有关内置函数anyall的文档。
  2. 请参阅Counter上的文档。

推荐阅读