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

如何在LISP中从给定列表生成指定长度的所有连续子列表

Lisp 生成固定长度连续子列表实现方案

该需求在 Lisp 中完全可以实现,核心实现逻辑是逐次截取列表前N个元素,再将列表头部移除一位后递归执行,直到剩余列表长度不足N时终止。

Common Lisp 实现版本

(defun consecutive-sublists (lst n)
  (when (>= (length lst) n)
    (cons (subseq lst 0 n)
          (consecutive-sublists (cdr lst) n))))

调用示例:执行 (consecutive-sublists '(1 2 3 4 5 6) 4),即可得到预期结果 ((1 2 3 4) (2 3 4 5) (3 4 5 6))。

Scheme 实现版本

(define (consecutive-sublists lst n)
  (if (>= (length lst) n)
      (cons (take lst n)
            (consecutive-sublists (cdr lst) n))
      '()))

性能优化提示

如果需要处理超长列表,可优化长度判断逻辑,无需每次遍历计算全列表长度,改用两个相差N位的指针同步移动判断终止条件即可,运行效率更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 03:45:04