python - 检查模式是否在单词列表中
问题描述
我需要一个包含与模式完全相同的单词的输出 - 仅在相同位置的相同字母(并且字母不应在其他地方的单词中显示)和相同的长度,例如:
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)
谢谢 !
解决方案
您可以使用正则表达式:
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']
更远
推荐阅读
- python - OpenCV 图像处理后 QLabel 不更新图像
- android - 如何在捕获图像上添加时间戳?
- python - Python:未定义最小值
- amazon-web-services - 没有 AWS 凭证的 Terraform 运行计划
- python - 如何有条件地将一个列表中的元组附加到另一个元组列表?
- c# - EF Core One to Many adding new object
- c# - 在 Any at = IsAvailable = !b.BorrowHistories.Any(h => h.ReturnDate == null) 下获得一条红线
- c - INI 文件阅读器功能正在向我的结构寻址错误的值,我该如何解决?
- mysql - 如何在查询中执行递归查询或子查询?
- reactjs - 如何设置 react-final-form onSubmit 值参数类型 TypeScript