如何筛选并打印包含list1元素的list2列表项?
列表筛选解决方案
这是个很常见的文本匹配筛选需求,我给你写个简洁又健壮的实现代码:
list1 = ['home', 'school', 'bus', 'football'] list2 = ['yesterday I went to home', 'I am busy', 385723, 'I feel like playing football', 'I was tired last week', 'I go to school by bus',' there is a bus stop near my home', 'I am hungry'] for item in list2: # 先统一转成字符串,避免处理整数这类非字符串元素时报错 item_str = str(item) # 用any()快速判断是否包含list1中的任一关键词 if any(keyword in item_str for keyword in list1): # 用repr()输出带引号的格式,和你示例一致 print(repr(item_str))
代码细节说明
- 类型兼容处理:因为list2里有整数
385723这种非字符串元素,先转成字符串再判断,避免触发TypeError。 - 高效判断逻辑:
any()函数会在找到第一个匹配的关键词时就停止检查,比遍历所有关键词更高效。 - 输出格式匹配:用
repr()来输出带单引号的字符串格式,和你给出的示例效果一致。
运行这段代码后,会输出你预期的结果:
'yesterday I went to home'
'I feel like playing football'
'I go to school by bus'
' there is a bus stop near my home'
如果后续需要把结果存起来而不是直接打印,可以用列表推导式一次性生成结果列表:
filtered_list = [str(item) for item in list2 if any(keyword in str(item) for keyword in list1)] print(filtered_list)
这样filtered_list就保存了所有符合条件的项,方便后续的其他操作。
内容的提问来源于stack exchange,提问作者Moe
相关产品推荐
相关产品推荐

