朱莉娅:如何漂亮地打印数组?

时间:2020-07-13 03:34:52

标签: julia

a= zeros(4,4)

像这样打印a

> 4×4 Array{Float64,2}:
>  0.0  0.0  0.0  0.0
>  0.0  0.0  0.0  0.0
>  0.0  0.0  0.0  0.0
>  0.0  0.0  0.0  0.0

但是println(a)这样打印

[0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0]

如何在函数中以以前的方式“打印” a?我希望出于调试目的。

2 个答案:

答案 0 :(得分:5)

让我对这里发生的事情发表评论。如您在文档中所见,show(io, x)show(io, mime, x)之间的主要区别是:

help?> show(stdout,a) show([io :: IO = stdout],x)

将值x的文本表示形式写入输出流io。新型T 应该重载show(io :: IO,x :: T)。 show一般使用的表示形式 包括特定于Julia的格式和类型信息,并且应 可解析的Julia代码。

repr以字符串形式返回show的输出。

要为类型T的对象自定义可读文本输出,请定义 改用show(io :: IO,:: MIME“ text / plain”,:: T)。检查:compact IOContext 建议使用此类方法中的io属性,因为某些容器会显示其 通过:compact => true调用此方法。

所以:

  • show(不带MIME)写入对象的文本表示形式,
  • 带有MIME的
  • show试图产生一种人类可读的格式。

现在print(io, x)退回到show(io, x),如您在此处看到的那样:

function print(io::IO, x)
    lock(io)
    try
        show(io, x)
    finally
        unlock(io)
    end
    return nothing
end

display在REPL中默认情况下退回到show(io, mime, a)

function display(d::REPLDisplay, mime::MIME"text/plain", x)
    io = outstream(d.repl)
    get(io, :color, false) && write(io, answer_color(d.repl))
    if isdefined(d.repl, :options) && isdefined(d.repl.options, :iocontext)
        # this can override the :limit property set initially
        io = foldl(IOContext, d.repl.options.iocontext,
                   init=IOContext(io, :limit => true, :module => Main))
    end
    show(io, mime, x)
    println(io)
    nothing
end

(在两种情况下,我都从Base复制了定义,最终您都使用了默认的print(a)display(a)操作-跳过了过程中调用的方法)

您可以在Julia手册中找到有关here的更多信息。

因此,在您的情况下-正如田俊建议的那样,您可以使用display。同样只是为了表明一切都退回到show

julia> a = zeros(4,4);

julia> show(stdout, a)
[0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0]
julia> show(stdout, "text/plain", a)
4×4 Array{Float64,2}:
 0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0

答案 1 :(得分:5)

有时您想保存显示大小和类型的行。因此,另一个值得注意的选择是DelimitedFiles

julia> a= zeros(4,4);

julia> using DelimitedFiles; writedlm(stdout, a)
0.0     0.0     0.0     0.0
0.0     0.0     0.0     0.0
0.0     0.0     0.0     0.0
0.0     0.0     0.0     0.0