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

如何判断list_2的元素是否按原顺序存在于list_1中?

判断列表是否为另一列表的顺序一致子序列

需求说明

给定三个列表:

  • list_1: ['one', 'took', 'a', 'walk', 'yeah', 'i', 'watched', 'the', 'world', 'happens', 'now']
  • list_2: ['yeah', 'i', 'watched', 'the', 'world']
  • list_3: ['yeah', 'one', 'took', 'a', 'world', 'walk', 'i', 'the', 'happens', 'now', 'watched']

需要实现逻辑:判断list_2的元素是否按相同顺序出现在目标列表中(无需连续,不关心起始和结束位置)。预期结果:

  • list_1与list_2对比返回True
  • list_3与list_2对比返回False

实现代码

可以通过遍历主列表,逐个匹配子列表元素的方式实现:

def is_subsequence(sub_list, main_list):
    sub_idx = 0
    for item in main_list:
        if sub_idx < len(sub_list) and item == sub_list[sub_idx]:
            sub_idx += 1
    return sub_idx == len(sub_list)

# 测试案例
list_1 = ['one', 'took', 'a', 'walk', 'yeah', 'i', 'watched', 'the', 'world', 'happens', 'now']
list_2 = ['yeah', 'i', 'watched', 'the', 'world']
list_3 = ['yeah', 'one', 'took', 'a', 'world', 'walk', 'i', 'the', 'happens', 'now', 'watched']

print(is_subsequence(list_2, list_1))  # 输出: True
print(is_subsequence(list_2, list_3))  # 输出: False

代码逻辑说明

  1. 初始化子列表的索引sub_idx为0,用于追踪当前需要匹配的子列表元素
  2. 遍历主列表的每个元素:
    • 如果当前子列表索引未超出范围,且主列表元素与子列表当前索引元素匹配,则子列表索引加1
  3. 遍历结束后,若子列表索引等于子列表长度,说明所有元素按顺序匹配完成,返回True;否则返回False

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 23:45:34