gpt4 book ai didi

format - 固定宽度字段中的 pretty-print 值

转载 作者:太空宇宙 更新时间:2023-11-03 18:47:27 26 4
gpt4 key购买 nike

我想在固定宽度的字段中漂亮地打印一个由列名和值组成的矩阵。这是我写的代码:

(defstruct
(matrix
(:print-function (lambda (my-matrix stream depth)
(declare (ignore depth))
(let* ((dimensions (matrix-dimensions my-matrix))
(column-names (matrix-column-names my-matrix))
(values (matrix-values my-matrix))
(number-of-rows (nth 0 dimensions))
(number-of-columns (nth 1 dimensions)))
(progn (loop :for i :upto number-of-columns
:do (if (< i number-of-columns)
(format stream (nth i column-names))
(format stream "~%")))
(loop :for j :upto (1- number-of-rows)
:do (loop :for k :upto number-of-columns
:do (if (< k number-of-columns)
(format stream (write-to-string (aref values j k)))
(format stream "~%")))))))))
dimensions
column-names
values)

但是,如果我运行这段代码,这就是我得到的结果:

CL-USER> (make-matrix :dimensions '(3 2)
:column-names '("Michael" "Alexandra")
:values (make-array '(3 2) :initial-contents '((54 34) (65 78) (49 38))))
MichaelAlexandra
5434
6578
4938

如何编辑我的 :print-function(更具体地说是它的格式部分),以便列名和值都整齐地打印在固定宽度的字段中?

我读到有一个 ~w 指令用于此目的,但并没有真正理解它是如何工作的。

最佳答案

format指令中使用"~NN":

(defstruct
(matrix
(:print-function (lambda (my-matrix stream depth)
(declare (ignore depth))
(let* ((dimensions (matrix-dimensions my-matrix))
(column-names (matrix-column-names my-matrix))
(values (matrix-values my-matrix))
(number-of-rows (nth 0 dimensions))
(number-of-columns (nth 1 dimensions)))
(loop :for i :upto number-of-columns
:do (if (< i number-of-columns)
(format stream "~10s" (nth i column-names))
(terpri stream)))
(loop :for j :upto (1- number-of-rows)
:do (loop :for k :upto number-of-columns
:do (if (< k number-of-columns)
(format stream "~10s" (aref values j k))
(terpri stream))))))))
dimensions
column-names
values)

附言。在 let

中不需要 progn

关于format - 固定宽度字段中的 pretty-print 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26894147/

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