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

Common Lisp是否有Python itertools.starmap的等效实现?

Common Lisp 中类似 Python itertools.starmap 的功能

Common Lisp 标准库中没有直接对应 itertools.starmap 的同名函数,但可以通过现有核心工具轻松实现等价功能,主要有两种常见方式:

方式一:mapcar + apply 组合

利用 mapcar 遍历嵌套集合的每个子元素,再通过 apply 将目标函数作用于子集合的所有元素上,完全复刻 starmap 的逻辑:

;; 对应 Python 示例的求和场景
(let ((nested-list '((1 2) (3 4) (5 6) (0 0) (1 1) (2 2))))
  (mapcar #'(lambda (sub-collection) (apply #'+ sub-collection)) nested-list))
;; 返回结果:(3 7 11 0 2 4)

如果是自定义函数,写法也类似:

(defun add-two (x y) (+ x y))

(let ((nested-list '((1 2) (3 4) (5 6) (0 0) (1 1) (2 2))))
  (mapcar #'(lambda (pair) (apply #'add-two pair)) nested-list))
;; 同样返回:(3 7 11 0 2 4)

这种方式的优势是通用性强,不管子集合包含多少个元素都能适配。

方式二:loop 宏解构遍历

如果子集合的元素数量固定(比如示例中都是二元组),用 loop 宏直接解构子集合元素,写法更直观:

(let ((nested-list '((1 2) (3 4) (5 6) (0 0) (1 1) (2 2))))
  (loop for (x y) in nested-list
        collect (+ x y)))
;; 返回结果:(3 7 11 0 2 4)

内容的提问来源于stack exchange,提问作者J. Mini

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 19:25:20