Given a Vector
of Pair
s, what’s an idiomatic way of getting a vector of first and second elements in each Pair
? MWE:
x = [Pair(x,2*x) for x in 1:5]
then
julia> collect.(collect(zip(((a,b) for (a,b) in x)...))) # works, but convoluted
2-element Array{Array{Int64,1},1}:
[1,2,3,4,5]
[2,4,6,8,10]
1 Like
first.(x)
and last.(x)
works pretty well and is terse.
7 Likes
One possibility is
julia> [first(p) for p in x]
5-element Array{Int64,1}:
1
2
3
4
5
julia> [last(p) for p in x]
5-element Array{Int64,1}:
2
4
6
8
10
EDIT:
Which can be written as map(first, x)
and map(last, x)
I do agree that it is counterintuitive / unfortunate that two loops through are required.
2 Likes