Python中如何判断列表元素含指定子串并输出对应结果?
列表元素子串匹配问题修复
需求说明
遍历list1的每个元素:
- 若元素包含
list2中的任一子串,打印该子串 - 若两个子串都不包含,打印
not found
原代码及问题
原代码
list1 = ['moonlight black','mint cream','electric black','deep blue', 'black','blue','flowing silver','crystal blue','ink black'] list2 = ["blue","black"] for i in list1: for j in list2: if j in i: print(j) else: print("not found")
当前错误输出
not found black not found not found not found black blue not found not found black blue not found not found not found blue not found not found black
期望输出
black not found black blue black blue not found blue black
错误原因
原嵌套循环对每个list1元素都会遍历两次list2,每次判断都输出结果,导致每个元素对应两次输出,不符合“每个元素仅输出一次”的需求。
修复方案
方案1:使用标志位控制输出
通过标志位记录是否找到匹配的子串,找到后立即跳出内层循环,未找到则最终打印not found:
list1 = ['moonlight black','mint cream','electric black','deep blue', 'black','blue','flowing silver','crystal blue','ink black'] list2 = ["blue","black"] for item in list1: matched = False for keyword in list2: if keyword in item: print(keyword) matched = True break # 找到第一个匹配项就停止遍历 if not matched: print("not found")
方案2:使用next()函数简化代码
利用生成器表达式结合next()函数,直接获取第一个匹配的子串,无匹配则返回默认值not found,代码更简洁:
list1 = ['moonlight black','mint cream','electric black','deep blue', 'black','blue','flowing silver','crystal blue','ink black'] list2 = ["blue","black"] for item in list1: print(next((kw for kw in list2 if kw in item), "not found"))
两种方案运行后都能得到期望的输出结果。
内容的提问来源于stack exchange,提问作者Jagathkumar
相关产品推荐
相关产品推荐

