Nested list comprehensions in Julia

前端 未结 5 1037
无人共我
无人共我 2021-02-13 16:14

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]
         


        
5条回答
  •  猫巷女王i
    2021-02-13 16:20

    Any reason why you're using a tuple of vectors? It's much simpler with arrays, as Ben has already shown with vec. But you can also use comprehensions pretty simply in either case:

    julia> a = ([1,2,3],[4,5,6],[7,8,9]);
    julia> [i for i in hcat(a...)]
    9-element Array{Any,1}:
     1
     2
     ⋮
    

    The expression hcat(a...) "splats" your tuple and concatenates it into an array. But remember that, unlike Python, Julia uses column-major array semantics. You have three column vectors in your tuple; is that what you intend? (If they were row vectors — delimited by spaces — you could just use [a...] to do the concatenation). Arrays are iterated through all elements, regardless of their dimensionality.

提交回复
热议问题