在Julia中将集合转换为数组



如何在Julia中将Set转换为Array?

例如,我想将下面的Set转换为Array。

x = Set([1,2,3])
x
Set{Int64} with 3 elements:
2
3
1

collect()函数可用于此操作。例如

collect(x)
3-element Vector{Int64}:
2
3
1

但是,请注意,元素的顺序已经更改。这是因为集合是无序的。

您可以使用理解:

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})

您也可以在集合上使用splat运算符:

julia> [x...]
3-element Vector{Int64}:
2
3
1

但是,这比collect慢。

您可以使用[]创建数组。

x = Set([1,2,3])
y = [a for a in x]
y
2
3
1
typeof(y)
Vector{Int64} (alias for Array{Int64, 1})

最新更新