首页 > 解决方案 > 制作需要删除列表元素的循环脚本

问题描述

Python问题

import fnmatch

list_1 = ['family', 'brother', 'snake', 'famfor']

list_2 = ['a', 'f', 'f', 'm', 'i', 'l', 'y']

match = fnmatch.filter(list_1, 'fa????')

print match

这会给我

>> ['family', 'famfor']

我怎样才能在这个查询中只得到家人?通过检查 list_2 的有效字母。

标签: python

解决方案


您可以先转换list_2为集合以进行高效查找,然后使用带有条件的列表推导作为过滤器:

set_2 = set(list_2)
[w for w in list_1 if all(c in set_2 for c in w)]

这将返回:

['family']

推荐阅读