Ale*_*lec 2 arrays list-comprehension julia
如果我想创建一个具有理解力的数组,但逻辑要多行,该如何在Julia中做到这一点?
例如
[ ...logic... for x=1:10]
除非逻辑更清楚地用多行编写,最后一行产生我想要的内容?
map(iterator) do x 做这个:
map(1:5) do x
1+1 # this line is un-yielded logic that precedes the final value
x # this final line is what is returned in the resulting array
end
Run Code Online (Sandbox Code Playgroud)
结果是:
5-element Array{Int64,1}:
1
2
3
4
5
Run Code Online (Sandbox Code Playgroud)
通常,do语法是这类事情的首选,但请注意,这可以通过常规的数组理解来完成,您只需将其包装在括号中,并使用分号进行换行:
[(y = x + 1;
z = y^2 + x;
z^4 + 2y) for x in 1:5]
Run Code Online (Sandbox Code Playgroud)
结果是
5-element Array{Int64,1}:
629
14647
130329
707291
2825773
Run Code Online (Sandbox Code Playgroud)