Python列表字符串部分匹配:筛选包含指定关键词元素的实现问询
你的现有代码存在两个核心问题:
- 仅将lambda函数和
list_a作为两个独立元素存入list_c,没有触发过滤遍历逻辑 - lambda判断逻辑写反:你写的
x in list_b是判断字符串整体是否属于颜色列表,实际需要判断的是颜色列表中的任意元素是否存在于当前字符串中
正确实现方案
方案1:基于filter函数实现(贴合你原本想用lambda的写法)
list_a = ["the red bird is fast", "the blue bird lives in a green tree", "the yellow bird is very angry"] list_b = ["red", "green"] list_c = list(filter(lambda x: any(color in x for color in list_b), list_a))
方案2:列表推导式实现(可读性更高,更推荐)
list_a = ["the red bird is fast", "the blue bird lives in a green tree", "the yellow bird is very angry"] list_b = ["red", "green"] list_c = [sentence for sentence in list_a if any(color in sentence for color in list_b)]
运行后list_c的输出为:
["the red bird is fast", "the blue bird lives in a green tree"]
你预期输出里的"the blue bird lives in the green tree"属于笔误,上述实现会保留list_a中的原始文本内容。
内容的提问来源于stack exchange,提问作者forest
相关产品推荐
相关产品推荐

