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)]
?
Tuples in Julia are an immutable collection of distinct values of same or different datatypes separated by commas. Tuples are more like arrays in Julia except that arrays only take values of similar datatypes. The values of a tuple can not be changed because tuples are immutable.
The broadcast() is an inbuilt function in julia which is used to broadcast the function f over the specified arrays, tuples or collections.
Creating a Vector A Vector in Julia can be created with the use of a pre-defined keyword Vector() or by simply writing Vector elements within square brackets([]). There are different ways of creating Vector. vector_name = [value1, value2, value3,..] or vector_name = Vector{Datatype}([value1, value2, value3,..])
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 NamedTuple
s 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With