Python实现从列表筛选同时包含另外两个列表元素的项
从列表中筛选同时包含另外两个列表元素的项
需求说明
从目标列表中找出同时满足以下两个条件的元素:
- 元素包含第一个对比列表中的任意一个字符串
- 元素包含第二个对比列表中的任意一个字符串
示例输入
Paths = ['ab01', 'bc02', 'cd03', 'de04', 'ef05'] str1 = ['b','e'] str2 = ['3', '4']
解决方案
方法1:简洁的列表推导式
这是Python中最常用的简洁写法,利用any()函数快速判断元素是否包含目标子串:
out = [path for path in Paths if any(s in path for s in str1) and any(s in path for s in str2)] print(out) # 输出: ['de04']
方法2:可读性更强的函数写法
如果需要更清晰的逻辑拆分,可以封装成函数,方便复用:
def filter_target_paths(paths, required_group1, required_group2): matched_paths = [] for path in paths: # 检查是否包含第一组的任意元素 has_group1 = any(sub in path for sub in required_group1) # 检查是否包含第二组的任意元素 has_group2 = any(sub in path for sub in required_group2) if has_group1 and has_group2: matched_paths.append(path) return matched_paths out = filter_target_paths(Paths, str1, str2) print(out) # 输出: ['de04']
逻辑解释
any(sub in path for sub in group):遍历对比列表中的每个子串,只要有一个子串出现在当前path中,就返回True- 两个
any()结果用and连接,确保只有同时满足两组条件的元素才会被筛选出来
内容的提问来源于stack exchange,提问作者piyush
相关产品推荐
相关产品推荐

