在 Julia 中创建任何大小的“无”数组

Rom*_*n F 7 julia

在 Julia 中,可以使用函数zeros(.)或来创建任意大小的数组ones(.)。是否有类似的函数来创建一个nothing在初始化时填充但也接受浮点数的数组?我的意思是像这个例子中的函数:

a = array_of_nothing(3)
# a = [nothing,nothing,nothing]
a[1] = 3.14
# a = [3.14,nothing,nothing]
Run Code Online (Sandbox Code Playgroud)

我试图在互联网上查找信息,但没有成功......对不起,我是 Julia 的初学者。

DNF*_*DNF 8

fill函数可用于创建任意值的数组,但在这里使用起来并不容易,因为您需要一个Vector{Union{Float64, Nothing}}. 想到两个选项:

一个领悟:

a = Union{Float64, Nothing}[nothing for _ in 1:3];
a[2] = 3.14;

>> a
3-element Array{Union{Nothing, Float64},1}:
  nothing
 3.14    
  nothing
Run Code Online (Sandbox Code Playgroud)

或者普通的数组初始化:

a = Vector{Union{Float64, Nothing}}(undef, 3)
fill!(a, nothing)
a[2] = 3.14
Run Code Online (Sandbox Code Playgroud)

似乎当你做Vector{Union{Float64, Nothing}}(undef, 3)vector 时自动包含nothing,但我不会依赖它,所以fill!可能是必要的。

  • 你可以直接写“Vector{Union{Float64, Nothing}}(nothing, 3)”。关于依赖 `undef` 产生的内容,请参阅 https://github.com/JuliaLang/julia/pull/31091#discussion_r263588660。如果将单例与非单例混合,您将得到单例。 (3认同)

Viv*_*ivz 7

我认为您正在寻找Base.fill- 功能。

fill(x, dims)
Run Code Online (Sandbox Code Playgroud)

这将创建一个填充值 x 的数组。

println(fill("nothing", (1,3)))
Run Code Online (Sandbox Code Playgroud)

您还可以传递一个Foo()类似的函数fill(Foo(), dims),该函数将返回一个填充了Foo()一次评估结果的数组。