※上記の広告は60日以上更新のないWIKIに表示されています。更新することで広告が下部へ移動します。


集合を定義する

>>> s = set(["SPAM","Egg","SPAM","Bacon","Bacon"])
>>> print(s)
{'Bacon', 'Egg', 'SPAM'}

集合の要素数を取得する

>>> s = set(["SPAM","Egg","SPAM","Bacon","Bacon"])
>>> len(s)
3

集合に要素を追加する

>>> s = set(["SPAM","Egg","SPAM","Bacon","Bacon"])
>>> s.add("Sausage")
>>> print(s)
{'Bacon', 'Sausage', 'Egg', 'SPAM'}
>>> s.add("SPAM")
>>> print(s)
{'Bacon', 'Sausage', 'Egg', 'SPAM'}

集合から要素を削除する

>>> s = set(["SPAM","Egg","SPAM","Bacon","Bacon"])
>>> s.remove("SPAM")
>>> print(s)
{'Bacon', 'Egg'}
>>> s.discard("Bacon")
>>> print(s)
{'Egg'}
>>> s.discard("SPAM")
>>> print(s)
{'Egg'}

集合から要素を取り出す

>>> s = set([1,2,3,4,5])
>>> s.pop()
1
>>> print(s)
{2, 3, 4, 5}

集合の関係を求める

>>> s1 = set([1,2,3])
>>> s2 = set([1,2,3,4,5])
>>> s1 < s2
True
>>> s1 >= s2
False

集合の和を求める

>>> s1 = set([1,3,4])
>>> s2 = set([1,2,5,6])
>>> s1 | s2
{1, 2, 3, 4, 5, 6}

集合の差を求める

>>> s1 = set([1,3,4])
>>> s2 = set([1,2,5,6])
>>> s2 - s1
{2, 5, 6}

集合の積を求める

>>> s1 = set([1,3,4])
>>> s2 = set([1,2,5,6])
>>> s1 & s2
{1}

集合の排他的和を求める

>>> s1 = set([1,3,4])
>>> s2 = set([1,2,5,6])
>>> s1 ^ s2
{2, 3, 4, 5, 6}
>>> (s1|s2)-(s1&s2)
{2, 3, 4, 5, 6}


|