# Julia array slicing to list

I have A= [2 1;1 2;3 3;2 4;3 5;3 6;1 7;1 8;2 9],

I wanted to get the values in second column when column one have same values, as a separate list.

like— when first column value=1, [2,7,8]
similarly second column value= 2, [1,4,9] using a for loop.

Something like this?

``````julia> A[@view(A[:,1]) .== 1, 2]
3-element Vector{Int64}:
2
7
8

julia> A[@view(A[:,1]) .== 2, 2]
3-element Vector{Int64}:
1
4
9
``````
2 Likes
``````julia> [x => A[@view(A[:, 1]) .== x, 2] for x ∈ unique(A[:, 1])]
3-element Vector{Pair{Int64, Vector{Int64}}}:
2 => [1, 4, 9]
1 => [2, 7, 8]
3 => [3, 5, 6]
``````
3 Likes

although the description of the request is not entirely clear, I propose a solution in line with the others

``````
A= [2 1;1 2;3 3;2 4;3 5;3 6;1 7;1 8;2 9]

d=Dict{Int, Vector{Int}}()
for r in axes(A,1)
push!(get!(()->[],d, A[r,1]),A[r,2])
end
d
``````

or

``````
foreach(r->push!(get!(()->[],d, A[r,1]),A[r,2]),axes(A,1))

reduce((d,r)->merge(d, Dict(A[r,1]=>[get!(()->[],d, A[r,1]);[A[r,2]]])),axes(A,1), init=Dict{Int, Vector{Int}}())

``````

A suggested small tweak to Nils’ code above:

``````A = [2 1; 1 2; 3 3; 2 4; 3 5; 3 6; 1 7; 1 8; 2 9]
d = @views Dict(x => A[A[:,1] .== x, 2] for x ∈ unique(A[:,1]))
# then we can do:
d, d, d
``````
1 Like