Julia - 如何使用数组理解和三元运算符来初始化向量

Julia - How to use Array comprehension with ternary operator to initialize a vector

这是我想要的行为...

result = []
for element in iterable
    if(condition)
        push!(result, element)
    else 
        continue 
    end
end

但是当在 Julia 中使用带有三元运算符的数组理解时,我不确定除了不使用任何东西之外类似的“继续”会是什么。这会导致不需要的 Vector{Union{Nothing, ...}}。

result = [(condition ? element : nothing) for element in iterable]

例如:

vec1 = []
for v in -1:1
    if(v==0)
        push!(vec1,v)   
    else 
        continue   
    end 
end 

returns

julia> vec1 
1-element Vector{Any}:
0

同时

vec2 = [(v==0 ? v : nothing) for v in -1:1]

returns

julia> vec2 = [(v==0 ? v : nothing) for v in -1:1]        
3-element Vector{Union{Nothing, Int64}}:
nothing
0
nothing

而不只是普通的 Vector{Int64}

如果要使用 array comprehensions,可以使用 if 关键字:

julia> [x for x in -2:2 if iseven(x)]
3-element Vector{Int64}:
 -2
  0
  2

如果不需要使用数组推导式,可以使用filter:

julia> filter(iseven, -2:2)
3-element Vector{Int64}:
 -2
  0
  2

不可能使用如下结构: result = [(condition ? element : <SOMETHING>) for element in iterable] 因为这将始终保留输入可迭代对象的长度。相当于一张地图,不过看来你真的想要一个滤镜。