Python 集合型 frozenset
Publish date: 2021-03-25
Last updated: 2021-03-25
Last updated: 2021-03-25
frozensetはPythonの組み込み集合型でイミュータブルです。
frozensetの定義
s1 = frozenset([1, 2, 1, 1, 3])
s2 = frozenset({1, 2, 1, 1, 3})
s3 = frozenset((1, 2, 1, 1, 3))
s4 = frozenset(x+1 for x in range(3))
# => {1, 2, 3}
集合の濃度(サイズ)
s1 = frozenset({2, 3, 5, 7, 11})
len(s1) # => 5
要素の存在判定
s1 = frozenset({2, 3, 5, 7, 11})
len(s1) # => 5
2 in s1 # => True
4 not in s1 # => True
集合が等しいか
s1 = frozenset({1, 2, 3})
s2 = frozenset({1, 2, 3})
s3 = frozenset({1, 5, 7})
s1 == s1 # => True
s1 == s2 # => True
s1 == s3 # => False
s1 != s1 # => False
s1 != s2 # => False
s1 != s3 # => True
集合が共通部分を持たないか
s1 = frozenset({2, 3, 5, 7, 11})
s2 = frozenset({4, 6, 8, 10})
s3 = frozenset({5, 10})
s1.isdisjoint(s2) # => True
s2.isdisjoint(s3) # => False
集合の包含関係
部分集合・サブセット・下位集合
s1 = frozenset({2, 3, 5, 7, 11})
s2 = frozenset({2, 7})
s1.issubfrozenset(s1) # => True s1 ⊆ s1
s2.issubfrozenset(s1) # => True s2 ⊆ s1
s1.issubfrozenset(s2) # => False s1 ⊈ s2
s1 <= s1 # => True s1 ⊆ s1
s2 <= s1 # => True s2 ⊆ s1
s1 <= s2 # => False s1 ⊈ s2
真部分集合
s1 = frozenset({2, 3, 5, 7, 11})
s2 = frozenset({2, 7})
s1 < s1 # => False s1 ⊆ s1
s2 < s1 # => True s2 ⊊ s1
s1 < s2 # => False s1 ⊈ s2
s1.issubfrozenset(s1) and s1 != s1 # => False
s2.issubfrozenset(s1) and s2 != s1 # => True
s1.issubfrozenset(s2) and s1 != s2 # => False
上位集合・スーパーセット
s1 = frozenset({2, 3, 5, 7, 11})
s2 = frozenset({2, 7})
s1.issuperfrozenset(s1) # => True s1 ⊇ s1
s2.issuperfrozenset(s1) # => False s2 ⊉ s1
s1.issuperfrozenset(s2) # => True s1 ⊋ s2
s1 >= s1 # => True s1 ⊇ s1
s2 >= s1 # => False s2 ⊉ s1
s1 >= s2 # => True s1 ⊋ s2
真上位集合
s1 = frozenset({2, 3, 5, 7, 11})
s2 = frozenset({2, 7})
s1 > s1 # => False s1 ⊇ s1
s2 > s1 # => False s2 ⊉ s1
s1 > s2 # => True s1 ⊋ s2
s1.issuperfrozenset(s1) and s1 != s1 # => False
s2.issuperfrozenset(s1) and s2 != s1 # => False
s1.issuperfrozenset(s2) and s1 != s2 # => True
和集合
s1 = frozenset({2, 3, 5, 7, 11})
s2 = frozenset({2, 4, 6, 7})
s1.union(s2) # => {2, 3, 4, 5, 6, 7, 11}
s1 | s2 # => {2, 3, 4, 5, 6, 7, 11}
共通部分
s1 = frozenset({2, 3, 5, 7, 11})
s2 = frozenset({2, 4, 6, 7})
s1.intersection(s2) # => {2, 7}
s1 & s2 # => {2, 7}
差集合
s1.difference(s2) # => {3, 5, 11}
s2.difference(s1) # => {4, 6}
s1 - s2 # => {3, 5, 11}
s2 - s1 # => {4, 6}
対称差
s1 = frozenset({2, 3, 5, 7, 11})
s2 = frozenset({2, 4, 6, 7})
s1.symmetric_difference(s2) # => {3, 4, 5, 6, 11}
s1 ^ s2 # => {3, 4, 5, 6, 11}
コピー
s1 = frozenset({2, 3, 5, 7, 11})
s2 = s1.copy()
s2 # => {2, 3, 5, 7, 11}