arrays - 通用 Lisp : convert between lists and arrays

标签 arrays list common-lisp

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

例如

((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/

相关文章:

python - 如何在 python 中更改列表中的数字

python - 在 Python 中打印一列二维列表

java - 如何将列表转换为可读格式

output - SBCL 末尾的 'T' 是什么

common-lisp - 如何 (zerop #*000) 在普通 lisp 中?

arrays - 如何在 Swift 3 中将十六进制转换为十进制? (没有第三方库和Foundation的自写代码)

c++ - 是否可以在声明后设置 constexpr 数组中元素的值?

lisp - 常见的 Lisp 练习/问题

javascript - 我正在尝试通过单击按钮从我的数组中生成一个随机词

javascript - Javascript 中的名称索引 - 数组/对象?