Set 是一组元素,具有以下特性:
用Set()构造函数创建,参数可以是任意迭代器。
julia> s1 = Set(1:4)
Set{Int64} with 4 elements:
4
2
3
1
用push!()添加新元素(和数组一样),用delete!()删除元素。
julia> push!(s1, 5)
Set{Int64} with 5 elements:
5
4
2
3
1
# Duplicates are ignored
julia> push!(s1, 3)
Set{Int64} with 5 elements:
5
4
2
3
1
julia> delete!(s1, 5)
Set{Int64} with 4 elements:
4
2
3
1
julia> length(s1) # length counts entries, despite the non-sequential type
4
和其他几种集合类型一样,可以用in或∈运算符检查元素是否属于集合(输入\in后按 Tab 即可打出这个符号)。
julia> 3 ∈ s1
true
支持以下针对两个 Set 的运算(运算符符号的快捷输入方式写在括号里)。
union(A, B)或A ∪ B(\cup):属于 A 或 B 或同时属于两者的所有元素。intersect(A, B)或A ∩ B(\cap):同时属于 A 和 B 的所有元素。setdiff(A, B)(无符号):在 A 中但不在 B 中的元素。symdiff(A, B)(无符号):只属于 A 或只属于 B 的元素,不同时属于两者。issubset(A, B)或A ⊆ B(\subseteq)或B ⊇ A(\supseteq):如果 A 的所有元素也都在 B 中,则为true。issetequal(A, B)(无符号):如果 A 和 B 包含完全相同的元素,则为true。isdisjoint(A, B)(无符号):如果 A 和 B 没有任何共同的元素(即交集为空),则为true。s1 = Set(1:4)
s2 = Set(3:6)
julia> s1 ∪ s2 # union
Set{Int64} with 6 elements:
5
4
6
2
3
1
julia> s1 ∩ s2 # intersect
Set{Int64} with 2 elements:
4
3
julia> setdiff(s1, s2)
Set{Int64} with 2 elements:
2
1
julia> symdiff(s1, s2)
Set{Int64} with 4 elements:
5
6
2
1
julia> s1 ⊇ s2 # issubset
false
其中许多运算还有会就地修改集合的版本,只需在函数名后加上!。
完整的函数列表见手册。