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]
to get [1,2,3,4,5,6]
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?
Don't have enough reputation for comment so posting a modification @ben-hammer. Thanks for the example of flatten(), it was helpful to me.
But it did break if the tuples/arrays contained strings. Since
strings
are iterables the function would further break them down to characters. I had to insert condition to check forASCIIString
to fix that. The code is belowYou can get some mileage out of using the splat operator with the array constructor here (transposing to save space)
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: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.List comprehensions work a bit differently in Julia:
If
a=[[1 2],[3 4],[5 6]]
was a multidimensional array,vec
would flatten it:Since a contains tuples, this is a bit more complicated in Julia. This works, but likely isn't the best way to handle it:
Then, we can run:
This feature has been added in julia v0.5: