如何像数组理解一样过滤映射?

Ale*_*lec 5 julia

使用数组,您可以根据条件进行过滤:

[i for i=1:10 if isodd(i) ]
Run Code Online (Sandbox Code Playgroud)

返回:

5-element Vector{Int64}:
 1
 3
 5
 7
 9
Run Code Online (Sandbox Code Playgroud)

但尝试类似的map结果会产生nothing值:

julia> map(1:10) do i
           isodd(i) ? i : nothing
           end
Run Code Online (Sandbox Code Playgroud)

结果:

10-element Vector{Union{Nothing, Int64}}:
 1
  nothing
 3
  nothing
 5
  nothing
 7
  nothing
 9
  nothing
Run Code Online (Sandbox Code Playgroud)

Jun*_*ian 10

map是一对一的映射。所以恐怕你不能对 做同样的事情map。也许您正在寻找的只是filter

julia> a = 1:10
1:10

julia> filter(isodd, a)
5-element Vector{Int64}:
 1
 3
 5
 7
 9
Run Code Online (Sandbox Code Playgroud)