PrinceOfBorgo
PrinceOfBorgo

Reputation: 590

Build array iterating over multiple indices in Julia

I want to obtain the following result with a more elegant syntax

julia> collect(Iterators.flatten([[(x,y) for y in 1:x] for x in 1:3]))
6-element Array{Tuple{Int64,Int64},1}:
 (1, 1)
 (2, 1)
 (2, 2)
 (3, 1)
 (3, 2)
 (3, 3)

I tried something like [(x,y) for y in 1:x, x in 1:3] but I get ERROR: UndefVarError: x not defined.

Upvotes: 3

Views: 658

Answers (2)

Jun Tian
Jun Tian

Reputation: 1390

I used to have also been struggled to remember the variable order. Until one day someone told me a secret: just treat the order of for loop in the list comprehension as usual except that the body is moved to the front.

For example, in normal order we write:

for x in 1:3
    for y in 1:x
        # do sth
    end
end

Now we move the body part to the front and we have [ #= do sth =# for x in 1:3 for y in 1:x]

Upvotes: 3

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69869

Just reverse the order of variables like this:

julia> [(x,y) for x in 1:3 for y in 1:x]
6-element Array{Tuple{Int64,Int64},1}:
 (1, 1)
 (2, 1)
 (2, 2)
 (3, 1)
 (3, 2)
 (3, 3)

Upvotes: 4

Related Questions