You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何实现两个列表循环遍历直到找到匹配元素

双列表循环匹配遍历实现方案

问题原因

原有代码每次遍历out_list元素时仅对in_list索引做一次递增,未匹配场景下不会持续向后查找in_list元素,因此到第三个out元素时无法找到对应匹配项。

修复后代码

in_list = [1,2,2,1,3,4]
out_list = [1,2,3,2,1,4]
len_in = len(in_list)
index = 0

for out in out_list:
    # 循环查找直到匹配当前out元素
    while in_list[index % len_in] != out:
        print(out, in_list[index % len_in])
        print('loop until match')
        index += 1
    # 匹配成功逻辑
    print(out, in_list[index % len_in])
    print('match')
    index += 1

实现说明

  • 通过index % len_in计算in_list的实际访问下标,实现循环遍历效果,不会出现索引越界问题
  • 新增内层while循环,未匹配到当前out元素时会持续递增索引向后查找,直到匹配成功才处理下一个out元素,确保每个out元素都能输出match

内容的提问来源于stack exchange,提问作者Stack Vau

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 09:15:02