朱莉娅的嵌套列表推导 [英] Nested list comprehensions in 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 ]
在朱莉娅中嵌套列表的理解是否可能?
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
这篇关于朱莉娅的嵌套列表推导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文