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

Python如何查找子列表在父列表中所有出现的起始索引

实现方案

完整可运行代码

def listInList(list1, list2):
    len1 = len(list1)
    len2 = len(list2)
    res = []
    # 子列表为空或子列表长度超过目标列表直接返回空
    if len2 == 0 or len2 > len1:
        return res
    # 遍历所有合法的起始索引位置
    for i in range(len1 - len2 + 1):
        # 切片匹配子列表
        if list1[i:i+len2] == list2:
            res.append(i)
    return res

list1 = [0,0,0,0,1,0,1,0,0,0,1,0,1,0,0]
list2 = [1,0,1]
print(listInList(list1, list2))

运行后输出结果为[4, 10],符合要求。

逻辑说明

  • 先做边界校验,避免无意义的遍历计算
  • 遍历范围控制在0到len(list1)-len(list2),保证截取的切片长度始终和子列表一致,不会出现越界
  • 直接通过Python原生列表切片比对判断是否匹配,写法简洁可读性高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 10:36:03