Pythonの集合操作と重複排除テクニック

集合の基本操作

Pythonの集合は数学的な集合演算をサポートしています。以下は主要な集合操作の例です。

集合演算の実例

set_a = {'食事', '睡眠'}
set_b = {'食事', '睡眠', '旅行', 'ゲーム', '読書', '運動'}

# 共通部分(積集合)
intersection = set_a & set_b
print(f"共通要素: {intersection}")

# 和集合
union = set_a | set_b
print(f"全要素: {union}")

# 差集合
difference_ab = set_b - set_a
difference_ba = set_a - set_b
print(f"B-Aの差: {difference_ab}")
print(f"A-Bの差: {difference_ba}")

# 対称差
symmetric_difference = set_a ^ set_b
print(f"対称差: {symmetric_difference}")

# 包含関係
print(f"AはBの部分集合: {set_a.issubset(set_b)}")
print(f"BはAの上位集合: {set_b.issuperset(set_a)}")

集合による重複排除

リストの重複除去

# 単純なリストの重複除去
items = ['apple', 'banana', 'apple', 'orange', 'banana']
unique_items = list(set(items))
print(f"重複除去後: {unique_items}")

複雑なデータ構造の重複除去

# 辞書リストの重複除去
students = [
    {'name': '山田', 'score': 85},
    {'name': '佐藤', 'score': 92},
    {'name': '山田', 'score': 85},
    {'name': '鈴木', 'score': 78},
    {'name': '佐藤', 'score': 92}
]

# タプル変換による重複除去
unique_students = []
seen = set()
for student in students:
    # 辞書をハッシュ可能なタプルに変換
    student_tuple = tuple(student.items())
    if student_tuple not in seen:
        seen.add(student_tuple)
        unique_students.append(student)
        
print(f"重複除去後の学生リスト: {unique_students}")

集合のメソッド操作

要素の追加と更新

numbers = {10, 20, 30, 40}

# 複数要素の追加
numbers.update([40, 50, 60])
print(f"更新後の集合: {numbers}")

# 単一要素の追加
numbers.add(70)
print(f"要素追加後: {numbers}")

要素の削除

sample_set = {1, 2, 3, 4, 5}

# removeメソッド(要素が存在しない場合はエラー)
sample_set.remove(3)
print(f"remove後: {sample_set}")

# discardメソッド(要素が存在しない場合もエラーなし)
sample_set.discard(10)  # 存在しない要素
print(f"discard後: {sample_set}")

集合の比較

set_x = {1, 2, 3}
set_y = {1, 2, 3, 4, 5}

print(f"XはYの部分集合: {set_x <= set_y}")
print(f"YはXの上位集合: {set_y >= set_x}")
print(f"集合の等価性: {set_x == {1, 2, 3}}")

タグ: Python set 集合演算 重複排除 データ構造

8月11日 23:19 投稿