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

如何在Python中判断列表A是否为列表B的连续子序列?

Checking if one list is a contiguous sublist of another in Python

Great question! What you're describing is exactly checking if list A is a contiguous sublist (sometimes called a consecutive subsequence or subarray) of list B—this mirrors how the in operator behaves for strings, where it checks for a consecutive match of characters.

First, let's clarify the terminology

The key term you might have missed is contiguous sublist (or subarray). Using this phrase instead of broader terms like "sublist" (which can sometimes refer to non-consecutive elements) will help you find more targeted solutions quickly.

Simple implementations

Method 1: Leverage string in operator (quick but with caveats)

If your list elements are simple types (like integers, strings without commas) that can be safely converted to unique string representations, you can convert both lists to strings and use the built-in in operator—super concise:

def containedin(a, b):
    # Handle edge case: empty list is always a contiguous sublist
    if not a:
        return True
    # Join elements with a separator to avoid ambiguous matches (e.g., 12 vs 1+2)
    str_a = ','.join(map(str, a))
    str_b = ','.join(map(str, b))
    return str_a in str_b

Testing this with your examples:

print(containedin([2, 3, 4], [1, 2, 3, 4, 5]))          # True
print(containedin([2, 3, 4], [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]))  # False
print(containedin([2, 3, 4], [5, 4, 3, 2, 1]))          # False
print(containedin([2, 2, 2], [1, 2, 3, 4, 5]))          # False
print(containedin([2, 2, 2], [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]))  # False
print(containedin([2, 2, 2], [1, 1, 1, 2, 2, 2, 3, 3, 3]))  # True

Caveat: This won't work if your elements contain commas or can produce ambiguous string outputs (e.g., an element like "1,2" would clash with the separator we use).

Method 2: Slice comparison (robust, works for all element types)

For a more general solution that works with any element type (as long as they can be compared for equality), iterate over possible starting positions in B and compare slices to A:

def containedin(a, b):
    len_a, len_b = len(a), len(b)
    # If A is longer than B, it can't be a sublist
    if len_a > len_b:
        return False
    # Check every possible slice of B with length equal to A
    for i in range(len_b - len_a + 1):
        if b[i:i+len_a] == a:
            return True
    return False

This method is reliable for all cases, including lists with duplicate elements or complex objects (as long as the == operator works correctly for those objects). If you want to treat empty lists as valid contiguous sublists, just add if not a: return True at the start.

Why your earlier searches didn't find the right answers

Many Stack Overflow results for "sublist" focus on non-consecutive elements or basic membership checks (e.g., "are all elements of A present in B"). Using the term contiguous sublist or subarray will narrow down results to exactly the behavior you're looking for.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:58:31