集合型とタプル型

開発者のためのPython入門

Jasmin Ludolf

Senior Data Science Content Developer

集合型

  • 一意的なデータを含む

  • 変更不可

    • 値の追加・削除は可能だが、変更は不可
  • 重複を識別して削除するのに向いている

  • 他のデータ型(リストなど)と比べて速く検索できる

開発者のためのPython入門

集合を作成する

  • 集合 = {}
  • : = 辞書
  • :なし = 集合
# Create a set of ingredients
ingredients = {"pasta", "tomatoes", "pasta", 
                 "basil", "garlic", "olive oil", "salt"}
print(ingredients)
{'pasta', 'tomatoes', 'garlic', 'basil', 'olive oil', 'salt'}
開発者のためのPython入門

集合に変換する

# Existing list variable
ingredients_list = ["pasta", "tomatoes", "garlic", "basil"
                    "olive oil", "pasta", "salt"]


# Convert to a set unique_ingredients = set(ingredients_list)
# Check the data type type(unique_ingredients)
set
開発者のためのPython入門

集合に変換する

print(unique_ingredients)
{'pasta', 'tomatoes', 'garlic', 'basil', 'olive oil'}
開発者のためのPython入門

集合の制約

  • インデックスがない
    • 重複がない
    • []{{3}} でサブセット化できない
# Trying to subset a set
print(unique_ingredients[0])
TypeError: 'set' object is not subscriptable
開発者のためのPython入門

集合の並べ替え

ingredients = {"pasta", "tomatoes", "garlic", 
                 "basil", "olive oil", "salt"}


# Sorting a set print(sorted(ingredients))
['basil', 'garlic', 'olive oil', 'pasta', 'salt', 'tomatoes']
  • sorted() はリストを返す
開発者のためのPython入門

タプル型

  • イミュータブル - 変更できない
    • 値を追加できない
    • 値を削除できない
    • 値を変更できない
  • 順序がある
    • インデックスでサブセット化可能: [0]
  • 位置情報や識別子に役立つ

Padlock on top of a laptop

1 https://unsplash.com/@towfiqu999999
開発者のためのPython入門

タプルの作成

# Creating a tuple
serving_sizes = (1, 2, 4, 6, 8)


# Convert another data structure to a tuple ingredients_tuple = tuple(ingredients_list)
開発者のためのPython入門

タプルの取り出し

# A tuple
serving_sizes = (1, 2, 4, 6, 8)

# Access the second element
print(serving_size[1])
2
開発者のためのPython入門

練習しましょう!

開発者のためのPython入門

Preparing Video For Download...