在python中我可以做嵌套列表推导,例如我可以展平以下数组:
a = [[1,2,3],[4,5,6]]
[i for arr in a for i in arr]
Run Code Online (Sandbox Code Playgroud)
要得到 [1,2,3,4,5,6]
如果我在Julia中尝试这种语法,我会得到:
julia> a
([1,2,3],[4,5,6],[7,8,9])
julia> [i for arr in a for i in arr]
ERROR: syntax: expected ]
Run Code Online (Sandbox Code Playgroud)
Julia中的嵌套列表推导可能吗?
Jef*_*son 14
此功能已添加到julia v0.5中:
julia> a = ([1,2,3],[4,5,6],[7,8,9])
([1,2,3],[4,5,6],[7,8,9])
julia> [i for arr in a for i in arr]
9-element Array{Int64,1}:
1
2
3
4
5
6
7
8
9
Run Code Online (Sandbox Code Playgroud)
列表理解在Julia中的工作方式略有不同:
> [(x,y) for x=1:2, y=3:4]
2x2 Array{(Int64,Int64),2}:
(1,3) (1,4)
(2,3) (2,4)
Run Code Online (Sandbox Code Playgroud)
如果a=[[1 2],[3 4],[5 6]]是一个多维数组,vec会使它变平:
> vec(a)
6-element Array{Int64,1}:
1
2
3
4
5
6
Run Code Online (Sandbox Code Playgroud)
由于包含元组,这在Julia中有点复杂.这有效,但可能不是处理它的最佳方式:
function flatten(x, y)
state = start(x)
if state==false
push!(y, x)
else
while !done(x, state)
(item, state) = next(x, state)
flatten(item, y)
end
end
y
end
flatten(x)=flatten(x,Array(Any, 0))
Run Code Online (Sandbox Code Playgroud)
然后,我们可以运行:
> flatten([(1,2),(3,4)])
4-element Array{Any,1}:
1
2
3
4
Run Code Online (Sandbox Code Playgroud)
您可以在此处使用带有数组构造函数的splat 运算符获得一些好处(转置以节省空间)
julia> a = ([1,2,3],[4,5,6],[7,8,9])
([1,2,3],[4,5,6],[7,8,9])
julia> [a...]'
1x9 Array{Int64,2}:
1 2 3 4 5 6 7 8 9
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6041 次 |
| 最近记录: |