gpt4 book ai didi

arrays - 通用 Lisp : convert between lists and arrays

转载 作者:行者123 更新时间:2023-12-02 09:02:54 24 4
gpt4 key购买 nike

我们如何在任意嵌套的列表和数组之间优雅地转换?

例如

((1 2 3) (4 5 6))

变成了

#2A((1 2 3) (4 5 6))

反之亦然

最佳答案

列表到二维数组:

(defun list-to-2d-array (list)
(make-array (list (length list)
(length (first list)))
:initial-contents list))

要列出的二维数组:

(defun 2d-array-to-list (array)
(loop for i below (array-dimension array 0)
collect (loop for j below (array-dimension array 1)
collect (aref array i j))))

将列表转换为二维的多维形式很简单。

(defun list-dimensions (list depth)
(loop repeat depth
collect (length list)
do (setf list (car list))))

(defun list-to-array (list depth)
(make-array (list-dimensions list depth)
:initial-contents list))

要列出的数组更复杂。

也许是这样的:

(defun array-to-list (array)
(let* ((dimensions (array-dimensions array))
(depth (1- (length dimensions)))
(indices (make-list (1+ depth) :initial-element 0)))
(labels ((recurse (n)
(loop for j below (nth n dimensions)
do (setf (nth n indices) j)
collect (if (= n depth)
(apply #'aref array indices)
(recurse (1+ n))))))
(recurse 0))))

关于arrays - 通用 Lisp : convert between lists and arrays,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9549568/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com