Python | set 集合型(データ構造)

スポンサーリンク
Python
スポンサーリンク

集合型

集合とは、重複する要素をもたない、順序づけられていない要素の集まり。

集合は和集合(union)、積集合(intersection)、差集合(difference)、対称差 (symmetric difference)といった数学的な演算もサポートしている。
中括弧、またはset()関数は集合を生成するために使用することができる。

集合の特徴

1,集合は複数追加しても同じものは1つだけ持つことができる
2,イミュータブル(変更不可)なものしか入らない
3,順序がないため実行のたびに順番が変わる
4,{}を使う
5,リストより高速

使ってみよう

#集合を生成
alpa_1 = set('abcdefghalgjseac')
alpa_2 = set('jajhsahalkhekhfk')

print(alpa_1)
print(alpa_2)
#出力結果
#同じものは1つだけ出力される
#{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'l', 's'}
#{'a', 'e', 'f', 'h', 'j', 'k', 'l', 's'}

result1 = alpa_1 - alpa_2
print(result1)

#出力結果
#{'g', 'c', 'b', 'd'}

result2 = alpa_1 | alpa_2
print(result2)

#出力結果
#{'g', 'l', 'k', 's', 'a', 'b', 'd', 'c', 'f', 'h', 'j', 'e'}

result3 = alpa_1 & alpa_2
print(result3)

#出力結果
#{'l', 's', 'a', 'f', 'h', 'j', 'e'}

result4 = alpa_1 ^ alpa_2
print(result4)

#出力結果
#{'g', 'k', 'b', 'd', 'c'}

#内包表記
alpa_3 = {x for x in alpa_1 if x not in 'abc'} 
print(alpa_3)

#出力結果
#{'g', 'l', 's', 'd', 'f', 'h', 'j', 'e'}

集合のメソッド(追加・更新・削除)

items = {'cake'}
print('items :',items)

#1要素を削除
#pop() 何れかの要素を削除し返す。
result = items.pop()
print('items.pop():', result)
print('items :', items)

#リストを追加
#update(iterable)  イテラブルiterableの要素全てを追加する。
items.update(['apple', 'orange'])
print("items.update(['apple','orange'])")
print(items)

#全削除
#clear()   全ての要素を削除する。
items.clear()
print('items.clear()')
print('items :',items)

#追加
#add(item) itemを追加する。
items.add('painapple')
print("items.add('painapple')")
print('items :',items)

#削除
#remove(item)  itemを削除する。itemが存在しないとエラー(KeyError)になる。
items.remove('painapple')
print("items.remove('painapple')")
print('items :',items)

"""
#remove()はitemが無いとエラーになる
items.remove('apple')
print(items)

Traceback (most recent call last):
  File "set_method.py", line 59, in 
    items.remove('apple')
KeyError: 'apple'
"""

#削除
#discard(item) itemを削除する。itemが存在しなくてもエラーにならない。
items.discard('apple')
print("items.discard('apple')")
print('items :',items)

出力結果

items : {'cake'}
items.pop(): cake
items : set()
items.update(['apple','orange'])
{'apple', 'orange'}
items.clear()
items : set()
items.add('painapple')
items : {'painapple'}
items.remove('painapple')
items : set()
items.discard('apple')
items : set()

コメント