Ale*_*lec 4 list-comprehension julia
在 1d 中,我可以使用以下任一方法:
[i for i in 1:5]
Run Code Online (Sandbox Code Playgroud)
或者
map(1:5) do i
i
end
Run Code Online (Sandbox Code Playgroud)
两者都产生
[1,2,3,4,5]
Run Code Online (Sandbox Code Playgroud)
有没有办法map在更高维度上使用?例如复制
[x + y for x in 1:5,y in 10:13]
Run Code Online (Sandbox Code Playgroud)
产生
5×4 Array{Int64,2}:
11 12 13 14
12 13 14 15
13 14 15 16
14 15 16 17
15 16 17 18
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
julia> map(Iterators.product(1:3, 10:15)) do (x,y)
x+y
end
3×6 Array{Int64,2}:
11 12 13 14 15 16
12 13 14 15 16 17
13 14 15 16 17 18
Run Code Online (Sandbox Code Playgroud)
你写的理解我认为只是collect(x+y for (x,y) in Iterators.product(1:5, 10:13)),。注意括号(x,y),因为do函数得到一个元组。与x,y获取两个参数时不同:
julia> map(1:3, 11:13) do x,y
x+y
end
3-element Array{Int64,1}:
12
14
16
Run Code Online (Sandbox Code Playgroud)
这当然不是map您正在寻找的等价物,但在某些情况下,您可以使用带有向量和转置向量的广播:
x = 1:5
y = (10:13)'
x .+ y
Run Code Online (Sandbox Code Playgroud)
在 REPL:
x = 1:5
y = (10:13)'
x .+ y
Run Code Online (Sandbox Code Playgroud)