How to broadcast vectors (lists) into tuples in Julia?

Viewed 486

Is there a generator/iterator function that will turn

a = [1,2]
b = [3,4]

into [(1,3),(2,4)] and

a = 1
b = [3,4]

into [(1,3),(1,4)] using the same expression?

Is there a similar way to create a named tuple such as [(a=1,b=3),(a=1,b=4)]?

2 Answers

You can use broadcasting with Julia's dot syntax for this:

julia> tuple.(a, b)
2-element Array{Tuple{Int64,Int64},1}:
 (1, 3)
 (2, 4)

tuple here is a function that just creates a tuple from its arguments.

For NamedTuples you can either call the lower-level constructor directly on tuples with

julia> NamedTuple{(:a, :b)}.(tuple.(a, b))
2-element Array{NamedTuple{(:a, :b),Tuple{Int64,Int64}},1}:
 (a = 1, b = 3)
 (a = 2, b = 4)

where :a and :b are the sorted key names, or equivalently, using an anonymous function:

julia> broadcast((a_i, b_i) -> (a=a_i, b=b_i), a, b)
2-element Array{NamedTuple{(:a, :b),Tuple{Int64,Int64}},1}:
 (a = 1, b = 3)
 (a = 2, b = 4)

Hope that helps!

Just broadcast the tuple function.

julia> a = [1,2]; b=[3,4];


julia> tuple.(a,b)
2-element Array{Tuple{Int64,Int64},1}:
 (1, 3)
 (2, 4)

julia> tuple.(1, b)
2-element Array{Tuple{Int64,Int64},1}:
 (1, 3)
 (1, 4)

Second question - broadcast the constructor:

julia> NamedTuple{(:a, :b)}.(tuple.(1, b))
2-element Array{NamedTuple{(:a, :b),Tuple{Int64,Int64}},1}:
 (a = 1, b = 3)
 (a = 1, b = 4)
Related