且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Julia 中的嵌套列表推导

更新时间:2023-11-29 08:21:46

列表推导在 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