73
71

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Pythonの集合演算

Last updated at Posted at 2017-06-02

はじめに

集合に関してすぐ忘れちゃうのですよ

集合とは

  • 集合とは、重複する要素をもたない、順序づけられていない要素の集まり
  • {}内にカンマ区切りで要素を配置するか、set関数にシーケンス型を渡すことで生成
演算種 説明
和(union) A か B に含まれる
積(intersection) A と B で共通
差(difference) A にのみ含まれる
対称差(symmetric difference) A もしくは B にのみ含まれる

Setオブジェクトを用いて以下のような数学的な演算を行える

和(union)

A か B に含まれる

>>> {1, 2, 3} | {2, 3, 4}  # 和
{1, 2, 3, 4}

または

>>> a = {1, 2, 3}
>>> b = {2, 3, 4}
>>> a.union(b)
{1, 2, 3, 4}

元の集合を変更する場合

>>> a = {1, 2, 3}
>>> b = {2, 3, 4}
>>> a.update(b)
{1, 2, 3, 4}
>>> a
{1, 2, 3, 4}

積(intersection)

A と B で共通

>>> {1, 2, 3} & {2, 3, 4}  # 積
{2, 3}

または

>>> a = {1, 2, 3}
>>> b = {2, 3, 4}
>>> a.intersection(b)
{2, 3}

元の集合を変更する場合

>>> a = {1, 2, 3}
>>> b = {2, 3, 4}
>>> a.intersection_update(b)
>>> a
{2, 3}

差(difference)

A にのみ含まれる

>>> {1, 2, 3} - {2, 3, 4}  # 差
{1}

または

>>> a = {1, 2, 3}
>>> b = {2, 3, 4}   
>>> a.difference(b)
{1}

元の集合を変更する場合

>>> a = {1, 2, 3}
>>> b = {2, 3, 4}
>>> a.difference_update(b)
>>> a
{1}

対称差(symmetric difference)

A もしくは B にのみ含まれる

>>> {1, 2, 3} ^ {2, 3, 4}  # 対象差
{1, 4}

または

>>> a = {1, 2, 3}
>>> b = {2, 3, 4}
>>> a.symmetric_difference(b)
{1, 4}

元の集合を変更する場合

>>> a = {1, 2, 3}
>>> b = {2, 3, 4}
>>> a.symmetric_difference_update(b)
>>> a
{1, 4}

部分集合(subset)かの判定

左辺の要素すべてが右辺の集合に含まれている場合

>>> {1, 3} <= {1, 2, 3}
True

左辺の要素すべてが右辺の集合に含まれていない場合

>>> {1, 4} <= {1, 2, 3}
False

おわりに

Pythonたのし~

73
71
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
73
71

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?