Python Set intersection() メソッド
説明
intersection() メソッドは、2つ以上のセットに含まれる要素、つまり共通部分(インターセクション)を返すために使用します。
構文
intersection() メソッドの構文:
set.intersection(set1, set2 ... etc)
パラメータ
- set1 -- 必須。共通要素を検索するセット
- set2 -- 任意。共通要素を検索する他のセット。複数指定可能で、複数指定する場合はカンマ , で区切ります
戻り値
新しいセットを返します。
例
集合 x と集合 y の両方に含まれる要素を持つ新しいセットを返します:
例 1
x = {"apple", "banana", "cherry"}
y = {"google", "サンプル", "apple"}
z = x.intersection(y)
print(z)
出力結果は次のとおりです:
{'apple'}
複数のセットの共通部分を計算する:
例 1
x = {"a", "b", "c"}
y = {"c", "d", "e"}
z = {"f", "g", "c"}
result = x.intersection(y, z)
print(result)
出力結果は次のとおりです:
{'c'}