如何对比模板列表与单词列表筛选匹配单词?无需逐字符校验方案
筛选符合模板的单词的简便方法
不用逐个统计字母、取索引再校验,直接用Python的zip()函数就能轻松实现匹配逻辑,核心思路是把模板和单词的字符一一配对,批量检查每一位的匹配规则:
实现代码(基础版)
alist = [] template = ['_', '_', 'l', '_', '_'] words = ['hello', 'jacky', 'helps'] for word in words: # 先筛掉长度和模板不一样的单词 if len(word) != len(template): continue # 逐位对比模板和单词字符 is_match = True for t_char, w_char in zip(template, word): # 模板位不是_,且和单词字符不相等的话,直接判定不匹配 if t_char != '_' and t_char != w_char: is_match = False break if is_match: alist.append(word) print(alist) # 输出结果:['hello', 'helps']
更简洁的写法(列表推导式)
用all()函数简化判断逻辑,一行搞定筛选:
template = ['_', '_', 'l', '_', '_'] words = ['hello', 'jacky', 'helps'] alist = [ word for word in words if len(word) == len(template) and all(t == '_' or t == w for t, w in zip(template, word)) ] print(alist) # 输出结果:['hello', 'helps']
逻辑说明
- 先判断单词长度和模板长度是否一致,长度不符直接排除
zip(template, word)会把模板的每个字符和单词对应位置的字符配对成元组all(...)会检查所有配对是否满足:要么模板位是_(允许任意字符),要么字符和模板指定的字母完全相同,全部满足才判定匹配
内容的提问来源于stack exchange,提问作者micheal cay
相关产品推荐
相关产品推荐

