本文介绍了Julia 中的嵌套列表推导的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 python 中,我可以进行嵌套列表推导,例如,我可以将以下数组展平:
In python I can do nested list comprehensions, for instance I can flatten the following array thus:
a = [[1,2,3],[4,5,6]]
[i for arr in a for i in arr]
获取[1,2,3,4,5,6]
如果我在 Julia 中尝试这种语法,我会得到:
If I try this syntax in Julia I get:
julia> a
([1,2,3],[4,5,6],[7,8,9])
julia> [i for arr in a for i in arr]
ERROR: syntax: expected ]
在 Julia 中可以嵌套列表推导式吗?
Are nested list comprehensions in Julia possible?
推荐答案
列表推导在 Julia 中的工作方式有点不同:
List comprehensions work a bit differently in Julia:
> [(x,y) for x=1:2, y=3:4]
2x2 Array{(Int64,Int64),2}:
(1,3) (1,4)
(2,3) (2,4)
如果 a=[[1 2],[3 4],[5 6]]
是一个多维数组,vec
会将其展平:
If a=[[1 2],[3 4],[5 6]]
was a multidimensional array, vec
would flatten it:
> vec(a)
6-element Array{Int64,1}:
1
2
3
4
5
6
由于 a 包含元组,这在 Julia 中有点复杂.这可行,但可能不是处理它的最佳方法:
Since a contains tuples, this is a bit more complicated in Julia. This works, but likely isn't the best way to handle it:
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))
然后,我们可以运行:
> flatten([(1,2),(3,4)])
4-element Array{Any,1}:
1
2
3
4
这篇关于Julia 中的嵌套列表推导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!