0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonのset(集合)メソッドの図解

Posted at

Pythonのset(集合)は、ものの集まりを扱うのに便利な機能です。
この記事では、setの基本的なメソッドを図を使って説明します。

set(集合)って何?

setは、ものの集まりを表すことができます。例えば、

  • 好きな果物の集まり(りんご、みかん、ぶどう)

みたいな感じです。setでは、同じものが2つ以上入ることはありません。

setの主なメソッド

setには、いくつかの便利な機能(メソッド)があります。その中でも、特によく使うものを紹介します。

1. 和集合(union)

2つのsetを合わせて、全部の要素を集めたものです。

set1 = {"りんご", "みかん"}
set2 = {"みかん", "ぶどう"}
set1.union(set2) # 結果:{"りんご", "みかん", "ぶどう"}

図で表すと、以下のようになります。

       set1         set2
    +--------+    +--------+
    | りんご |    | みかん |
    | みかん |    | ぶどう |
    +--------+    +--------+
          \       /
           \     /
            \   /
         +-----------------+
         | りんご, みかん, ぶどう |
         +-----------------+

2. 積集合(intersection)

2つのsetに共通して含まれる要素を集めたものです。

set1 = {"りんご", "みかん"}
set2 = {"みかん", "ぶどう"}
set1.intersection(set2) # 結果:{"みかん"}

図で表すと、以下のようになります。

       set1         set2
    +--------+    +--------+
    | りんご |    | みかん |
    | みかん |    | ぶどう |
    +--------+    +--------+
          \       /
           \     /
            \   /
         +--------+
         | みかん |
         +--------+

3. 差集合(difference)

最初のsetにあって、2番目のsetにない要素を集めたものです。

set1 = {"りんご", "みかん"}
set2 = {"みかん", "ぶどう"}
set1.difference(set2) # 結果:{"りんご"}

図で表すと、以下のようになります。

       set1         set2
    +--------+    +--------+
    | りんご |    | みかん |
    | みかん |    | ぶどう |
    +--------+    +--------+
          \       /
           \     /
            \   /
         +--------+
         | りんご |
         +--------+

4. 対称差(symmetric_difference)

2つのsetのどちらか片方だけに存在する要素を集めたものです。

set1 = {"りんご", "みかん"}
set2 = {"みかん", "ぶどう"}
set1.symmetric_difference(set2) # 結果:{"りんご", "ぶどう"}

図で表すと、以下のようになります。

       set1         set2
    +--------+    +--------+
    | りんご |    | みかん |
    | みかん |    | ぶどう |
    +--------+    +--------+
          \       /
           \     /
            \   /
         +---------------+
         | りんご, ぶどう |
         +---------------+

これらのメソッドを使うと、setに入っている要素を色々と操作することができます。

まとめ

  • 和集合:2つのsetの要素を全部集める
  • 積集合:2つのsetに共通する要素を集める
  • 差集合:最初のsetにあって、2番目のsetにない要素を集める
  • 対称差:2つのsetのどちらか片方だけに存在する要素を集める
0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?