Reputation: 759
How can I convert a Set to an Array in Julia?
E.g. I want to transform the following Set to an Array.
x = Set([1,2,3])
x
Set{Int64} with 3 elements:
2
3
1
Upvotes: 10
Views: 4058
Reputation: 81
You can use a comprehension:
x = Set(1:5)
@time y = [i for i in x]
> 0.000006 seconds (2 allocations: 112 bytes)
typeof(y)
> Vector{Int64} (alias for Array{Int64, 1})
Upvotes: 2
Reputation: 1732
You can use [ ] to create an array.
x = Set([1,2,3])
y = [a for a in x]
y
2
3
1
typeof(y)
Vector{Int64} (alias for Array{Int64, 1})
Upvotes: 1
Reputation: 42244
You can also use the splat operator on sets:
julia> [x...]
3-element Vector{Int64}:
2
3
1
However, this is slower than collect
.
Upvotes: 1
Reputation: 759
The collect()
function can be used for this. E.g.
collect(x)
3-element Vector{Int64}:
2
3
1
Notice, however, that the order of the elements has changed. This is because sets are unordered.
Upvotes: 14