Julia 朱莉娅:如何漂亮地打印数组?
像这样打印Julia 朱莉娅:如何漂亮地打印数组?,julia,Julia,像这样打印a a= zeros(4,4) > 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)像这样打印 a= zeros(4,4) > 4×4 Array{Float64,2}: > 0.0 0.0 0.0 0.0 > 0.0 0.0
a
a= zeros(4,4)
> 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)
像这样打印
a= zeros(4,4)
> 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
如何在函数中以前一种方式“打印”a
?我希望它用于调试目的。使用显示(x)
让我在这里评论一下这里发生的事情。一个关键的区别是show(io,x)
和show(io,mime,x)
,正如您在文档中看到的:
帮助?>显示(stdout,a)
显示([io::io=stdout],x)
将值x的文本表示形式写入输出流io。新型T
应该显示重载(io::io,x::T)。show通常使用的表示法
包括特定于Julia的格式和类型信息,并且应
可能时可解析的Julia代码
repr以字符串形式返回show的输出
要自定义T类型对象的可读文本输出,请定义
改为显示(io::io,::MIME“text/plain”,::T)。检查:压缩IOContext
建议在此类方法中使用io属性,因为某些容器显示其
元素,通过使用:compact=>true调用此方法
因此:
不使用MIME写入对象的文本表示show
with MIME尝试生成一种人类可读的格式show
print(io,x)
fallsback到show(io,x)
如下所示:
[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]
默认情况下,REPL中的显示将返回到显示(io、mime、a):
(在这两种情况下,我都从基础复制了定义,最终使用默认的print(a)
和display(a)
操作-跳过过程中调用的方法)
你可以在Julia手册中找到更多关于它的信息
因此,在您的情况下-正如田军建议的,您可以使用显示
。也只是为了说明这一切都回到了show
:
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
有时,您希望保存显示大小和类型的行。因此,另一个值得注意的选项是
分隔文件
:
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
使用
display
?哇,我不知道这个,谢谢!的确,有时它是有用的,但对于大型阵列(尤其是浮点数阵列),它是有问题的,因为它不使用紧凑表示,也不考虑终端的水平和垂直大小。例如,比较rand(100100)
的display
和writedlm
的结果。