gpt4 book ai didi

Julia :如何漂亮地打印数组?

转载 作者:行者123 更新时间:2023-12-03 15:01:21 24 4
gpt4 key购买 nike

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?我希望出于调试目的。

最佳答案

让我在这里对这里发生的事情发表评论。您可以在docs中看到show(io, x)show(io, mime, x)之间的关键区别:

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

Write a text representation of a value x to the output stream io. New types Tshould overload show(io::IO, x::T). The representation used by show generallyincludes Julia-specific formatting and type information, and should beparseable Julia code when possible.

repr returns the output of show as a string.

To customize human-readable text output for objects of type T, defineshow(io::IO, ::MIME"text/plain", ::T) instead. Checking the :compact IOContextproperty of io in such methods is recommended, since some containers show theirelements by calling this method with :compact => true.


所以:

不带MIME的
  • show写入对象
  • 的文本表示形式
    带有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
    在REPL中,默认情况下, display会退回到 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的更多信息。
    因此,就您的情况而言-正如Jun Tian所建议的,您可以使用 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

    关于 Julia :如何漂亮地打印数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62868864/

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