嵌套列表匹配需求:找到匹配项后跳转至下一个子列表搜索
解决子列表字符串匹配与跳转搜索问题
需求说明
遍历list1的每个子列表,对每个子列表:
- 依次检查其中的每个字符串(关键词)
- 在
list2中找到第一个包含该关键词的元素 - 找到后立即停止当前子列表的剩余关键词检查,跳转至下一个子列表继续处理
- 最终返回每个子列表对应的匹配结果
代码实现
针对你给出的示例数据,以下是可行的解决方案:
list1 = [ ['test', 'string'], ['hello', 'world'], ['good', 'morning','everyone']] list2 = [ ['test is here'], ['hi everyone'], ['world of code']] # 存储每个子列表的匹配结果 match_results = [] for sublist in list1: current_match = None for keyword in sublist: # 已找到匹配,直接跳过当前子列表的剩余关键词 if current_match is not None: break # 遍历list2寻找匹配 for item in list2: # 你的list2元素是单元素列表,需取出内部字符串 content = item[0] if keyword in content: current_match = content break # 找到匹配后停止遍历list2 match_results.append(current_match) # 输出结果:['test is here', 'world of code', 'hi everyone'] print(match_results)
逻辑说明
- 外层循环遍历
list1的每个子列表,初始化current_match存储当前子列表的匹配结果 - 中层循环遍历子列表的关键词:若已找到匹配(
current_match不为空),直接跳出循环,处理下一个子列表 - 内层循环遍历
list2的元素:一旦检测到关键词在元素内容中,就记录匹配结果并停止内层循环 - 每个子列表处理完成后,将匹配结果存入结果列表
注意事项
如果你的list2元素本身是字符串(而非单元素列表,即list2 = ['test is here', 'hi everyone', 'world of code']),只需将代码中的content = item[0]改为content = item即可。
内容的提问来源于stack exchange,提问作者Nivek Duaner
相关产品推荐
相关产品推荐

