比如我有三个数组如下:
arr01 = [1 2 3];
arr02 = [1.0 2.0 3.0];
arr03 = ["1" "2" "3"];
我想将这三个数组以一下格式输出到一个文件中:
arr_all = [arr01; arr02; arr03];
using DelimitedFiles
open("myfile.dat", "w") do io
writedlm(io, arr_all)
end
但是arr_all 的类型不稳定是:Array{Any,2}.
所以我该如何做才能得到: 文件?
将他们全部转化成字符串是一种方法,但是转化本身也是需要时间的。
你是想要得到的数组稳定还是保存成文件之后再重新读取的时候类型稳定,前者的话应该是要先定义类型arry_all
的类型,后者的话是因为使用DelimitedFiles
之后得到的文件会损失类型,可以保存为jld2
或者HDF5
类型二进制文件,Serialization
貌似也可。如 @azurefx 所说,使用CSV
,或者DataFrames
按列保存也是可以的,这个我不知道会不会也损失精度啥的,存疑。
julia> arr_all = Array{Union{Int64,Float64,String},2}(undef,3,3)
3×3 Array{Union{Float64, Int64, String},2}:
#undef #undef #undef
#undef #undef #undef
#undef #undef #undef
julia> @views for i in 1:3
if i == 1
arr_all[i,:] =arr01
elseif i==2
arr_all[i,:] = arr02
else
arr_all[i,:] =arr03
end
end
julia> arr_all
3×3 Array{Union{Float64, Int64, String},2}:
1 2 3
1.0 2.0 3.0
"1" "2" "3"
上面的if-end
语句写的有点丑,我不会循环变量arr12345。。