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

如何遍历列表中任意固定长度的所有连续子数组

遍历固定长度连续子数组的实现方法

核心逻辑

对于长度为n的列表,长度为x的连续子数组的起始索引取值范围为 0 ≤ i ≤ n - x,总共有 n - x + 1 个符合要求的子数组,利用列表切片即可快速提取对应位置的子数组。

Python 实现

基础版本(一次性返回所有子数组)

def get_fixed_length_subarrays(lst: list, x: int) -> list:
    n = len(lst)
    # 非法输入校验
    if x <= 0 or x > n:
        raise ValueError(f"子数组长度x需满足 1 ≤ x ≤ {n}")
    return [lst[i:i+x] for i in range(n - x + 1)]

测试示例

listt = [2, 0, 5, 4, 2]
# 测试x=2
print(get_fixed_length_subarrays(listt, 2))
# 输出:[[2, 0], [0, 5], [5, 4], [4, 2]]

# 测试x=3
print(get_fixed_length_subarrays(listt, 3))
# 输出:[[2, 0, 5], [0, 5, 4], [5, 4, 2]]

生成器版本(节省内存,适合超长列表)

如果处理的列表长度极大,不需要一次性拿到所有子数组,可以用生成器按需返回,减少内存占用:

def gen_fixed_length_subarrays(lst: list, x: int):
    n = len(lst)
    if x <= 0 or x > n:
        raise ValueError(f"子数组长度x需满足 1 ≤ x ≤ {n}")
    for i in range(n - x + 1):
        yield lst[i:i+x]

# 遍历使用示例
for subarr in gen_fixed_length_subarrays(listt, 2):
    print(subarr)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 03:36:01