3.8. セット¶
3.8.1. セットの基本¶
セットはディクショナリと同じように「 {} 」(ブレース)を使用します。
1 2 3 4 5 6 7 | test_set_1 = {'first', '-', 'second', '.', 'third'}
print(test_set_1)
test_set_1 = {'first', '.', 'third', '-', 'second'}
print(test_set_1)
print('--------------------------------')
for i in test_set_1:
print(i)
|
出力
{'first', 'second', 'third', '-', '.'}
{'first', 'second', 'third', '-', '.'}
--------------------------------
first
second
third
-
.
要素がない空のセットを作成する時は「set」を用います。
1 2 3 4 5 6 7 8 | # これはディクショナリ
test_dict = {}
# これはセット
test_set = {'first'}
# 空のセットは「set」を使う
empty_set = set()
|
前述の通り、重複した値を持つことはできません。たとえば次の例では「'first'」と「'second'」が重複していますが、そのセットの出力結果には1つだけしか存在していません。
1 2 3 4 5 6 | test_set_1 = {'first', '-', 'second', '.', 'third', 'first', 'second'}
print(test_set_1)
print('--------------------------------')
for i in test_set_1:
print(i)
|
出力
{'first', 'third', '.', 'second', '-'}
--------------------------------
first
third
.
second
-
3.8.2. 要素の追加¶
単一の要素を追加する場合は「add」、他のセットやリスト、タプルなどから要素を追加する場合は「update」を使用します。
1 2 3 4 5 6 | test_set_1 = set()
test_set_1.add('first')
test_set_1.update({'-', 'second', '.', 'third'})
print (test_set_1)
|
出力
{'first', 'second', 'third', '.', '-'}
3.8.3. 要素の削除¶
セットから要素を削除する場合は「remove」「discard」を使用します。「remove」は指定した要素が存在していない場合はエラーとなります。
1 2 3 4 5 6 | test_set_1 = {'first', '-', 'second', '.', 'third'}
test_set_1.remove('-')
test_set_1.discard('.')
print (test_set_1)
|
出力
{'first', 'second', 'third'}
3.8.4. frozenset¶
frozensetは「frozenset」関数を使用して通常のsetのように作成できます。ただし次の例にあるような「remove」や「discard」、さらに「add」や「update」などを行おうとするとAttributeErrorが発生します。
1 2 3 4 5 6 | test_set_1 = frozenset({'first', '-', 'second', '.', 'third'})
# test_set_1.remove('-')
# test_set_1.discard('.')
print (test_set_1)
|
出力
frozenset({'-', 'first', 'third', 'second', '.'})